开发者

Problem converting PNG to JPG using Java (ImageIO.write()) [duplicate]

This question already has answers here: Issue using ImageIO.write jpg file: pi开发者_如何学JAVAnk background [closed] (6 answers) Closed 9 years ago.

I am using ImageIO.write() to convert PNG files to JPG. For some reason, my result image has a pink layer over it. I have searched far and wide for a solution but haven't found any. The code works for all other types of images except PNG.


I'm not sure how the other code snippet works given buffer is not used after it's created. I've found this pink problem to be jvm version specific.

The easiest solution I've found is to do this.

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


Quick reading of other SO answers tagged ImageIO led to this.

The root cause can be a buggy reader. The proposed workaround is using different reader package.

Edit Above link is broken, but this appears to be it.

Edit The above links are broken, here it is on archive.org.


I too had the same problem, but if i write it in png format then it gets solved.

Something like this,

ImageIO.write(resizedImageBuffer, "png", baos);


I found this link which has some code that might be of use. I tried your code with a few of my images but I couldn't reproduce the issue. I tried the last answer by devyn_a and it didn't break anything. Here's your code modified with devyn_a's solution.

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));

It would be interesting to know if this resolves the issue.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜