ImageIO.write(img, "jpg" ,pathtosave) JAVA 未将图像文件保存到选定的文件路径



我在VSCode IDE中使用JVM 14.0.2。该代码的目的是将原始输入图像更改为灰度图像,并将新的灰度图像保存到所需位置。

代码运行时没有任何异常,我尝试打印一些进度行(System.out.println("Saving completed…"((,在我插入的整个程序中打印的那些行。但是,当我转到选定的文件路径搜索保存的灰度图像时,我在目录中看不到新图像。

然后我尝试了BlueJ IDE,灰色图像被保存了下来。你能检查一下是VSCode开发环境问题还是我的代码问题吗?或者我需要一个不同的类/方法来编辑VSCode中的图像?谢谢你的帮助。如果你需要更多细节,请告诉我。

public class GrayImage {
public static void main(String args[]) throws IOException {
BufferedImage img = null;
// read image
try {
File f = new File("C:\original.jpg");
img = ImageIO.read(f);
// get image width and height
int width = img.getWidth();
int height = img.getHeight();
BufferedImage grayimg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
// convert to grayscale
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
Color color = new Color(img.getRGB(x, y));
int r = (int) color.getRed();
int g = (int) color.getBlue();
int b = (int) color.getGreen();
// calculate average
int avg = (r + g + b) / 3;
// replace RGB value with avg
Color newColor = new Color(avg, avg, avg, color.getAlpha());
grayimg.setRGB(x, y, newColor.getRGB());
}
}
// write image
System.out.println("Trying to write the new image...");
File newf = new File("H:\gray.jpg");
ImageIO.write(grayimg, "jpg", newf);
System.out.println("Finished writing the new image...");
} catch (IOException e) {
System.out.println(e);
}
}// main() ends here

}

如果我正确理解了这个问题,这里的重要教训是ImageIO.write(...)返回一个boolean,指示它是否成功。即使没有异常,也应该处理值为false的情况。有关参考,请参见API文档。

类似于:

if (!ImageIO.write(grayimg, "JPEG", newf)) {
System.err.println("Could not store image as JPEG: " + grayimg);
}

现在,您的代码确实在一个JRE中工作,而在另一个JRE不工作的原因可能与图像类型为TYPE_INT_ARGB(即包含alpha通道(有关。这曾经在Oracle JDK/JRE中工作,但已删除支持:

以前,Oracle JDK在提供可选的颜色空间支持时,使用了对广泛使用的IJG JPEG库的专有扩展。这被用于支持PhotoYCC和具有阿尔法成分的图像的读写。Oracle JDK 11中已删除了此可选支持。

修复很容易;由于您的源文件是JPEG文件,它可能无论如何都不包含alpha组件,因此您可以更改为不包含alpha的其他类型。如果你想要一个灰色的图像,我相信最好的匹配是:

BufferedImage grayimg = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);

但是TYPE_INT_RGBTYPE_3BYTE_BGR也应该工作,如果您以后在彩色图像方面遇到同样的问题。

最新更新