问题
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.
回答1:
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.
回答2:
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
回答3:
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);
回答4:
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.
来源:https://stackoverflow.com/questions/1830063/problem-converting-png-to-jpg-using-java-imageio-write