Javax.imageio.ImageIO reading invalid RGB values ​​in grayscale images

I have an image, name it grayscale.jpg. Now I open this image in Gimp and change the color mode to RGB and save it as color.jpg. If I look at grayscale.jpg and color.jpg in any image viewer, they look exactly the same. But if I open images using javax.imageio.ImageIO

 import javax.imageio.ImageIO; input = ImageIO.read(new File("grayscale.jpg")); System.out.format("Grayscale value: %x\n", input.getRGB(200, 200)); input = ImageIO.read(new File("color.jpg")); System.out.format("Color value: %x\n", input.getRGB(200, 200)); 

The color image will return the correct value, say 0xff6c6c6c. A grayscale image will return a different, brighter, incorrect value, for example, 0xffaeaeae.

 Grayscale value: 0xffaeaeae // Incorrect (Lighter) Color value: 0xff6c6c6c // Correct 

In other words, javax.imageio.ImageIO thinks that grayscale images are much easier than they really are. How can I accurately read grayscale images?

Edit

There is more context. My users upload images that may be in grayscale. My Java runs on the server and performs quite complex image processing. Therefore, the ideal solution is to simply fix my Java code, rather than combining something with command line tools.

+4
source share
1 answer

Your test does not matter, because you are using JPEG, which is lost. Depending on the compression, you may have different color values. So, try the same with PNG, which is lossless.

You can use this image to verify javax.imageio correct. Convert this to grayscale with Gimp and make sure you save it as PNG. Then download both (this and the converted) in the same way. And compare in the for loop all the colors of the y axis.

enter image description here

Code example:

 BufferedImage inputGrayscale = ImageIO.read(new File("grayscale.png")); BufferedImage inputColor = ImageIO.read(new File("color.png")); for (int i = 0; i < 256; ++i) { System.out.printf(i + "Grayscale value: %x\n", inputGrayscale.getRGB(10, i)); System.out.printf(i + "Color value: %x\n", inputColor.getRGB(10, i)); System.out.println(); } 
-1
source

Source: https://habr.com/ru/post/1387234/


All Articles