How to get rgb values ​​of jpeg image in TYPE_3BYTE_BGR?

I have this image:

Google image

I would like to extract the RGB values ​​of this image in int[] . This is what I have done so far for PNG images:

 File f = new File("t.jpg"); BufferedImage img = ImageIO.read(f); int[] ib = img.getRGB(0, 0, img.getWidth(), img.getHeight(), null, 0, img.getWidth()); Color c = new Color(ib[0]); System.out.println(c.getRed() + " " + c.getGreen() + " " + c.getBlue()); 

But here I get this conclusion: 255 128 128 , which is not expected, since I clearly see (and checked in several image editors) that the pixel in (0,0) has these values 255 255 255 .

I noticed that the type returned by img.getType() is TYPE_3BYTE_BGR , so I assume the decoding problem is happening behind the scenes but I cannot figure out how to do this (or get a clearer idea of ​​what is going on).

Does anyone have a suggestion on how to decode this type correctly?

+4
source share
1 answer

After extensive testing of various solutions, I came up with an error for the com.sun.imageio.plugins.jpeg.JPEGImageReader class (the class used to decode JPEG files with the ImageIO class).

If I do this (Oracle recommended, as this should work with all JVMs and many other threads in SO):

 BufferedImage bi = ImageIO.read(new FileInputStream("t.jpg")); 

then I get a red image.

On the other hand, if I do:

 JPEGImageDecoder jpegDec = JPEGCodec.createJPEGDecoder(new FileInputStream("t.jpg")); BufferedImage bi = jpegDec.decodeAsBufferedImage(); 

then I get the image correctly decoded. (note that com.sun.image.codec.jpeg.JPEGCodec is a special Sun / Oracle JVM class and therefore this solution is not portable).

Finally, another approach that I was trying to use uses Toolkit.getDefaultToolkit().createImage() . The image is loaded asynchronously (a small flaw, in my opinion), but at least it can load the image correctly. I am not 100% sure that this latest solution is portable across all platforms / JVMs.

+2
source

All Articles