【发布时间】:2009-12-02 01:09:06
【问题描述】:
我正在使用 ImageIO.write() 将 PNG 文件转换为 JPG。出于某种原因,我的结果图像上面有一个粉红色的图层。我已经广泛搜索了解决方案,但没有找到任何解决方案。该代码适用于除 PNG 以外的所有其他类型的图像。
【问题讨论】:
标签: java javax.imageio
我正在使用 ImageIO.write() 将 PNG 文件转换为 JPG。出于某种原因,我的结果图像上面有一个粉红色的图层。我已经广泛搜索了解决方案,但没有找到任何解决方案。该代码适用于除 PNG 以外的所有其他类型的图像。
【问题讨论】:
标签: java javax.imageio
我不确定其他代码 sn-p 是如何工作的,因为缓冲区在创建后未使用。我发现这个粉色问题是特定于 jvm 版本的。
我发现的最简单的解决方案就是这样做。
BufferedImage image = null;
BufferedImage imageRGB = null;
// imageBytes is some png file you read
image = ImageIO.read(new ByteArrayInputStream(imageBytes));
// Attempt at PNG read fix
imageRGB = new BufferedImage(image.getWidth(),
image.getHeight(), BufferedImage.TYPE_INT_RGB);
// write data into an RGB buffered image, no transparency
imageRGB.setData(image.getData());
// return the RGB buffered image, or do ImageIO.write( ... );
return imageRGB; // fixed for jpeg
【讨论】:
imageRGB.createGraphics().drawImage(image, null, null); 可以代替。
快速阅读标记为 ImageIO 的其他 SO 答案导致 this。
根本原因可能是阅读器有问题。建议的解决方法是使用不同的阅读器包。
编辑上面的链接坏了,但this似乎是它。
编辑以上链接失效,here it is on archive.org。
【讨论】:
我也有同样的问题,但是如果我用png格式写它就可以解决了。
类似的,
ImageIO.write(resizedImageBuffer, "png", baos);
【讨论】:
我发现这个link 有一些可能有用的代码。我用我的一些图片尝试了你的代码,但我无法重现这个问题。我尝试了 devyn_a 的最后一个答案,它没有破坏任何东西。这是使用 devyn_a 的解决方案修改的代码。
String url = "file:///d:/teststuff/IMG_0393.JPG";
String to = "d:/teststuff/out.jpg";
BufferedImage oldImage = ImageIO.read(new URL(url));
BufferedImage buffer = new BufferedImage (oldImage.getWidth(),
oldImage.getHeight(), BufferedImage.TYPE_INT_RGB);
ImageIO.write(ImageIO.read(new URL(url)), "jpg", new File(to));
想知道这是否能解决问题。
【讨论】: