问题描述
我在VSCode IDE中使用JVM 14.0.2。 该代码的目的是将原始输入图像更改为灰度图像,并将新的灰度图像保存到所需位置。
代码无例外运行,我尝试打印一些进度行(System.out.println(“保存完成...”);),这些行在我插入的整个程序中打印。但是,当我转到选定的文件路径以搜索保存的GrayScale图像,我在目录中看不到新图像。
然后我尝试了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,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 doc。
类似的东西:
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中使用,但是支持为removed:
以前,Oracle JDK使用对广泛使用的IJG JPEG库的专有扩展来提供可选的色彩空间支持。 它用于支持PhotoYCC和在读取和写入时均具有alpha分量的图像。 Oracle JDK 11中已删除了此可选支持。
修复很容易;由于您的来源是JPEG文件,因此它可能始终不包含alpha组件,因此您可以更改为没有alpha的其他类型。当您需要灰色图像时,我认为最佳匹配将是:
BufferedImage grayimg = new BufferedImage(width,height,BufferedImage.TYPE_BYTE_GRAY);
但是TYPE_INT_RGB
或TYPE_3BYTE_BGR
也应该起作用,如果以后您遇到彩色图像的相同问题。