Question

I need to create a Color object out of the RGB color of a pixel (of a BufferedImage object which reads a PNG file, BufferedImage colorspace is BufferedImage.TYPE_4BYTE_ABGR). However on some colors there are problems, please see the code below and the output. I guess it's some kind of colorspace problem, but I don't know how to solve it ): Thanks for any hint!

// imagine some great loop for x,y around the following code
int color = myImage.getRGB(x, y);

Color c = new Color(myImage.getRGB(x, y));

if(c.getRGB() != color)
    System.out.println("fail " + color + " vs " + c.getRGB());

Output:

fail -116782582 vs -16119286
fail 0 vs -16777216
fail 117440511 vs -1
fail -1090519040 vs -16777216
fail 1488435127 vs -4737097
fail -1090453247 vs -16711423

and some more. If it helps: e.g. transparency becomes black. I guess the new Color object is using another colorspace than the BufferedImage, but I don't know how to set the colorspace for a new Color object? Or is the RGB information just not enough to recreate the color?

Was it helpful?

Solution

I think the problem is that you are throwing out the alpha information in the color. I think you need to do the following:

int color = myImage.getRGB(x, y);
ColorModel model = myImage.getColorModel();
Color c = new Color(color, model.hasAlpha());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top