java - 使用 TYPE_USHORT_GRAY 在java中读取黑白图像

标签 java image bufferedimage

我有以下代码来读取java中的黑白图片。

imageg = ImageIO.read(new File(path));    
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null),  BufferedImage.TYPE_USHORT_GRAY);
        Graphics g = bufferedImage.createGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();
        int w = img.getWidth();
        int h = img.getHeight();
        int[][] array = new int[w][h];
        for (int j = 0; j < w; j++) {
            for (int k = 0; k < h; k++) {
                array[j][k] = img.getRGB(j, k);
                System.out.print(array[j][k]);
            }
        }

如您所见,我已将 BufferedImage 的类型设置为 TYPE_USHORT_GRAY,并且我希望在两个 D 数组矩阵中看到 0 到 255 之间的数字。但我会看到“-1”和另一个大整数。谁能指出我的错误吗?

最佳答案

正如评论和答案中已经提到的,错误在于使用 getRGB() 方法,该方法将像素值转换为默认 sRGB 颜色空间中的打包 int 格式(TYPE_INT_ARGB)。在此格式中,-1 与“0xffffffff”相同,表示纯白色。

要直接访问未签名的像素数据,请尝试:

int w = img.getWidth();
int h = img.getHeight();

DataBufferUShort buffer = (DataBufferUShort) img.getRaster().getDataBuffer(); // Safe cast as img is of type TYPE_USHORT_GRAY 

// Conveniently, the buffer already contains the data array
short[] arrayUShort = buffer.getData();

// Access it like:
int grayPixel = arrayUShort[x + y * w] & 0xffff;

// ...or alternatively, if you like to re-arrange the data to a 2-dimensional array:
int[][] array = new int[w][h];

// Note: I switched the loop order to access pixels in more natural order
for (int y = 0; y < h; y++) {
    for (int x = 0; x < w; x++) {
        array[x][y] = buffer.getElem(x + y * w);
        System.out.print(array[x][y]);
    }
}

// Access it like:
grayPixel = array[x][y];

PS:查看@blackSmith 提供的第二个链接可能仍然是一个好主意,以实现正确的颜色到灰色的转换。 ;-)

关于java - 使用 TYPE_USHORT_GRAY 在java中读取黑白图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26093390/

相关文章:

image - LoadMask 图像 - extjs

wpf - 如何强制图像在 WPF 中保持纵横比?

java - 将图像置于 ImageView 的中心?

java - 获取 BufferedImage 的每像素位数

java - 将 Pi 提高到 -4 到 4

java - 无法在 FreeBSD 上运行 java 文件(java.net.SocketException Invalid argument)

java - 从 BufferedImage 渲染 Sprite 时出现问题

java - 如何在java中获取图像文件(BufferedImage)的格式(ex :jpen, png,gif)

java - 在监听器类中配置的套接字服务器阻止了 tomcat 的运行

java - 如何从 Java Swing 应用程序在默认浏览器中打开 HTML 文件?