I'm trying to read, rescale and save images within a Servlet. That's the relevant code:
BufferedImage image = ImageIO.read(file);
BufferedImage after = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
AffineTransform at = AffineTransform.getScaleInstance(factor, factor);
AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
after = scaleOp.filter(image, null);
ImageIO.write(after, "JPG", file));
The original file is a plain RGB-Jpeg, but when I open and save the file it comes out as a CMYK-Jpeg. That happens even if i don't rescale the image, just opening and closing the image causes the problem.
When I open PNGs or GIFs everything is fine. Does anybody know what to do here? I would expect ImageIO's read-Method to retain the original colorspace.
If there's another way comfortable way of reading jpeg's?
Thanks for any suggestions!
I have had the same problem, and found this page.
I tried the suggestion above of creating a BufferedImage with the right type and using it as the after image instead of null in the filter call; and that did indeed resolve the problem.
ImageIO.read
ignores all embedded metadata, including an embedded color profile, which defines how RBG values map to physical devices such as screens or printers.You could read the metadata separately and pass it to
ImageIO.write
, but it's easier to just convert the image to the (default) sRGB color space and ignore the metadata.If you don't mind losing the metadata, replace
with
From the documentation of
AffineTransformOp.filter
:If the color models for the two images do not match, a color conversion into the destination color model is performed.
You create
after
and then overwrite it withscaleOp.filter
. Is this correct? So yourafter
image may not be RGB even though you think it is? If you wantafter
to be RGB then you may need to 'draw'image
ontoafter
before you do the transform.