问题
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