運行我正在開發的一些代碼時遇到問題。Java - 執行目錄中新生成文件的功能
它應該這樣:
For all images within directory (x)
Read image
Convert to greyscale
Save to new directory (y)
For all images within new directory (y)
Read image
Convert to binary
Save to new directory (z)
End for
End for
我有300張,目前,到目前爲止,所有圖像都成功地轉換爲灰度圖像並保存到一個新的目錄。但是,二進制轉換是出現問題的地方,因爲它似乎沒有檢測到新目錄中的任何圖像,並且只有在目錄中已存在[image]文件才能執行代碼之前纔出現。
因此,下面是實際發生的事情:
All files in directory (x) are read
All files in directory (x) are converted to greyscale and saved to new directory (y)
All files in directory (y) are read
It appears that directory (y) is empty (but, in fact, contains 300 greyscale images)
Program ends
然而,當我運行程序第二次,或者與300個灰度圖像,甚至一個單一的圖像,directory (y)
圖像被成功轉換變成二進制;它只有在目錄中存在預先存在的圖像時才起作用,而不是在即時創建新轉換爲灰度圖像時。
的方法被稱爲如下:
public static void processFiles(){
processGreyscale();
System.out.println("Greyscale image conversion complete.\n");
processBinary();
System.out.println("Binary image conversion complete.\n");
}
我甚至曾嘗試添加方法之間的時間延遲調用,以允許該系統本身,以檢測新創建的[灰度]圖像更新(在directory (y)
),但這不作任何差和圖像僅被識別並轉換爲二進制當兩個條件都滿足:
- 有在
directory (y)
本圖像
- 代碼第二次運行或如果目錄中有任何[image]文件在之前代碼第一次執行。
有沒有辦法做到這一點,以便新創建的灰度圖像在創建後立即檢測到,然後轉換爲二進制?
非常感謝。
UPDATE:我對轉換爲灰度代碼如下:
try{
//Read in original image.
BufferedImage inputImg = ImageIO.read(image);
//Obtain width and height of image.
double image_width = inputImg.getWidth();
double image_height = inputImg.getHeight();
//New images to draw to.
BufferedImage bimg = null;
BufferedImage img = inputImg;
//Draw the new image.
bimg = new BufferedImage((int)image_width, (int)image_height, BufferedImage.TYPE_BYTE_GRAY);
Graphics2D gg = bimg.createGraphics();
gg.drawImage(img, 0, 0, img.getWidth(null), img.getHeight(null), null);
//Save new binary (output) image.
String fileName = "greyscale_" + image.getName();
File file = new File("test_images\\Greyscale\\" + fileName);
ImageIO.write(bimg, "jpg", file);
}
catch (Exception e){
System.out.println(e);
}
我將如何修改此添加flush()
和/或close()
功能?
更新:我也創建了打印後,每個成功的轉換和唯一的反饋我從binary
方法有一條線:java.lang.NullPointerException (BINARY) test_images\Greyscale\desktop.ini: processed successfully. Binary image conversion complete.
而應該說:(BINARY) images\298.jpg: processed successfully.
。
這是否有任何理由?我不明白爲什麼desktop.ini
文件被讀取/處理?
...如果一個文件被寫入並關閉,它可以立即從Java訪問。所以這可能是代碼有問題。我們看不到。 – 2012-02-20 23:20:04
你如何檢測文件?您確定在創建新文件時是否正確關閉了新文件? – DNA 2012-02-20 23:21:05
我現在已將相關代碼添加到了我的原始帖子中。 – MusTheDataGuy 2012-02-20 23:52:38