0

I have a grayscale height map, which I created in Photoshop, and I need to pass it to a Java program for processing. I am loading it by using the ImageIO.read(...) method and then converting it to grayscale with this code:

BufferedImage map = ImageIO.read(new File(...));
BufferedImage heightMap = new BufferedImage(map.getWidth(), map.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
heightMap.getGraphics().drawImage(map, 0, 0, null);
heightMap.getGraphics().dispose();

In Photoshop, pixel (0,0) has a value of 17. When I use heightMap.getData().getSample(0, 0, 0) or ((byte[])(heightMap.getRaster().getDataElements(0, 0, null)))[0] & 0xff, I get a value of 64.

Interestingly, when I run map.getRGB(0, 0)>>16&0xFF, I also get the value of 64.

How do I fix this and get a value of 17?

Thanks.

  • Why are you converting a grayscale image to a grayscale image? What does getType and getColorModel say on the original map? – john16384 Feb 11 '17 at 15:04
  • Because when I'm loading the image (PNG), it is being loaded as type 0 (TYPE_CUSTOM) and with ColorModel: #pixelBits = 32 numComponents = 2 color space = java.awt.color.ICC_ColorSpace@39d79bb0 transparency = 3 has alpha = true isAlphaPre = false. – Massimo Saliba Feb 11 '17 at 15:37

1 Answers1

0

The cause of this issue was the file format (PNG). In Photoshop, I had the canvas mode set to greyscale and 8 bits/channel. After completion, I was saving the image/height map as a PNG which caused Java to load the image as type 0 or TYPE_CUSTOM and caused the greyscale conversion to mess up, probably due to transparency.

Saving the image to JPEG made Java load the image directly into greyscale (TYPE_BYTE_GRAY) and both map.getData().getSample(0, 0, 0) and ((byte[])(map.getRaster().getDataElements(0, 0, null)))[0] & 0xff returned a value of 13. Not the perfect value, but way better than the 64.

P.S: As expected, this time map.getRGB(0, 0)>>16&0xFF returned the incorrect value of 64.