Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 1.5.0_16 corrupted colours when saving jpg image

i have a loaded image from disk (stored as a BufferedImage), which i display correctly on a JPanel but when i try to re-save this image using the command below, the image is saved in a reddish hue.

ImageIO.write(image, "jpg", fileName);

Note! image is a BufferedImage and fileName is a File object pointing to the filename that will be saved which end in ".jpg".

I have read that there were problems with ImageIO methods in earlier JDKs but i'm not on one of those versions as far as i could find. What i am looking for is a way to fix this issue without updating the JDK, however having said that i would still like to know in what JDK this issue was fixed in (if it indeed is still a bug with the JDK i'm using).

Thanks.

like image 555
Coder Avatar asked Jan 22 '23 03:01

Coder


2 Answers

Ok, solved my problem, it seems that i need to convert the image to BufferedImage.TYPE_INT_RGB for some reason. I think the alpha channels might not be handled correctly at some layer.

like image 175
Coder Avatar answered Jan 31 '23 21:01

Coder


I would first start by investigating if it is the BifferedImage color model that is the problem or the jpeg encoding. You could try changing the image type (3rd argument in the constructor), to see if that produces a difference, and also use the JPEGCodec directly to save the jpeg.

E.g.

 BufferedImage bufferedImage = ...;  // your image
 out = new FileOutputStream ( filename );
 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder ( out );
 JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam ( bufferedImage );
 encoder.setJPEGEncodeParam ( param );
 encoder.encode ( bufferedImage );
 out.close();

EDIT: changed text, it's the image type you want to change. See the link to the constructor.

like image 41
mdma Avatar answered Jan 31 '23 22:01

mdma