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.
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.