How to get the rgb values of a jpeg image in TYPE_3BYTE_BGR?

隐身守侯 提交于 2019-12-12 08:54:10

问题


I have this image:

I'd like to extract the RGB values of this image in an int[]. This is what I've 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 output: 255 128 128 which is not expected since I clearly see (and have verified in several image editors) that the pixel at (0,0) has these values 255 255 255.

I noticed that the type returned by img.getType() is equal to TYPE_3BYTE_BGR so I guess it's a decoding issue happening behind the scene but I can't figure out how to workaround it (or get a clearer understanding of what's happening).

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


回答1:


After extensive testing of different solutions, I came out with a bug for the class com.sun.imageio.plugins.jpeg.JPEGImageReader (the class used for the decoding of JPEGs by the ImageIO class).

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

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

then I get the redish image.

In 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 specific class of the Sun/Oracle JVM and thus this solution is not portable).

Finally, the other approach that I tried which works is using Toolkit.getDefaultToolkit().createImage(). The image is loaded asynchronously (small disadvantage in my opinion) but at least it could load my image properly. I'm not 100% sure that this last solution is portable on all platforms/JVMs though.



来源:https://stackoverflow.com/questions/11959626/how-to-get-the-rgb-values-of-a-jpeg-image-in-type-3byte-bgr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!