有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

图像处理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");
}

我甚至尝试在方法调用之间添加一个时间延迟,以允许系统更新自身,以便检测新创建的[greyscale]图像(在directory (y)),但这没有任何区别,只有在满足以下两个条件时才能识别图像并将其转换为二进制:

  1. directory (y)中存在图像
  2. 在第一次执行代码之前,如果目录中有任何[image]文件,代码将再次运行,或者

有没有一种方法可以做到这一点,以便新生成的灰度图像一经创建便可检测,然后转换为二进制图像

非常感谢

更新:我转换为灰度的代码如下:

    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文件


共 (3) 个答案

  1. # 1 楼答案

    您是否使用任何类型的缓冲区来写入新文件?在开始转换为二进制之前,请确保刷新并关闭它

    编辑:为什么要创建一个BuffereImage inputImg,然后直接将其分配给另一个BuffereImage变量img?我看不出有什么理由那样做

    在ImageIO之后。write()尝试在bimg中添加。刷新()

  2. # 3 楼答案

    我已经发现了问题所在,现在已经解决了问题

    感谢你们提供了有用的建议