Prevent image from changing color when written to a new TYPE_BYTE_INDEXED BufferedImage

Viewed 88

I've been working on optimizing color PNG images for storage size by using the TYPE_BYTE_INDEXED BufferedImage to limit the number of unique colors each image can contain. I noticed that when I save an existing image to this format, the white (255,255,255) background color becomes an off-white color (252,252,252).

Is there any way to prevent this color shift from happening? I found this question which has a solution but it feels very hacky and is much slower than the Graphics2D implementation of drawImage.

Here's my code currently that's producing this issue. The original image is being loaded as a TYPE_3BYTE_BGR BufferedImage.

BufferedImage image = ImageIO.read(imageOutputPath.toFile());
BufferedImage indexedImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_INDEXED);
Graphics2D g = indexedImage.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();

I know that this type of BufferedImage supports white as I've tried adding white margins around the image and it displays correctly but with the off-white image centered on the page. It just seems like the white in my image isn't converting correctly.

Any ideas and help would be greatly appreciated. Thanks!

0 Answers
Related