Problem converting PNG to JPG using Java (ImageIO.

2019-02-18 15:40发布

This question already has an answer here:

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.

4条回答
叼着烟拽天下
2楼-- · 2019-02-18 15:42

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.

查看更多
ら.Afraid
3楼-- · 2019-02-18 16:03

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
查看更多
走好不送
4楼-- · 2019-02-18 16:04

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.

查看更多
做个烂人
5楼-- · 2019-02-18 16:06

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);
查看更多
登录 后发表回答