简体   繁体   English

Java BufferedImage Raster中的灰度值不正确

[英]Incorrect grayscale values from Java BufferedImage Raster

I have a grayscale height map , which I created in Photoshop, and I need to pass it to a Java program for processing. 我有一个在Photoshop中创建的灰度高度图 ,需要将其传递给Java程序进行处理。 I am loading it by using the ImageIO.read(...) method and then converting it to grayscale with this code: 我通过使用ImageIO.read(...)方法加载它,然后使用以下代码将其转换为灰度:

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. 在Photoshop中,像素(0,0)的值为17。当我使用heightMap.getData().getSample(0, 0, 0)((byte[])(heightMap.getRaster().getDataElements(0, 0, null)))[0] & 0xff ,我得到的值是64。

Interestingly, when I run map.getRGB(0, 0)>>16&0xFF , I also get the value of 64. 有趣的是,当我运行map.getRGB(0, 0)>>16&0xFF ,我也得到了64的值。

How do I fix this and get a value of 17? 我该如何解决并获得17的值?

Thanks. 谢谢。

The cause of this issue was the file format (PNG). 此问题的原因是文件格式(PNG)。 In Photoshop, I had the canvas mode set to greyscale and 8 bits/channel. 在Photoshop中,我将画布模式设置为灰度和8位/通道。 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. 完成后,我将图像/高度图另存为PNG,这导致Java将图像加载为类型0TYPE_CUSTOM,并可能由于透明度而导致灰度转换混乱。

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. 将图像保存为JPEG使得Java将图像直接加载到灰度( TYPE_BYTE_GRAY )中,并且map.getData().getSample(0, 0, 0)((byte[])(map.getRaster().getDataElements(0, 0, null)))[0] & 0xff返回值13。这不是完美的值,但比64更好。

PS: As expected, this time map.getRGB(0, 0)>>16&0xFF returned the incorrect value of 64. PS:如预期的那样,这次map.getRGB(0, 0)>>16&0xFF返回了错误的值64。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM