[英]Handling of java.awt.Color while saving file (JPG) with ImageIO.write
[英]ImageIO.write(img,"jpg",pathtosave) JAVA not saving Image file to selected filepath
我在 VSCode IDE 中使用 JVM 14.0.2。 該代碼的目的是將原始輸入圖像更改為灰度圖像並將新的灰度圖像保存到所需位置。
代碼無一例外地運行,我嘗試打印一些進度行(System.out.println(“保存完成...”);),這些行在我插入的整個程序中打印。但是,當我轉到選擇文件路徑來搜索保存的灰度圖像,我在目錄中沒有看到新圖像。
然后我嘗試了 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工作,而不是在另一個,可能與類型的圖像感TYPE_INT_ARGB
(即包含Alpha通道)。 這曾經在 Oracle JDK/JRE 中工作,但支持已被刪除:
以前,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
應該可以工作,如果您以后遇到與彩色圖像相同的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.