运行我正在开发的一些代码时遇到问题。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