Java:从缓冲图像中获取 RGBA 作为整数数组

标签 java arrays pixel bufferedimage rgba

给定一个图像文件,例如 PNG 格式,如何获取表示位于 i 行 j 列的像素的 int [r,g,b,a] 数组?

到目前为止,我从这里开始:

private static int[][][] getPixels(BufferedImage image) {

    final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
    final int width = image.getWidth();
    final int height = image.getHeight();

    int[][][] result = new int[height][width][4];

    // SOLUTION GOES HERE....
}

提前致谢!

最佳答案

您需要获取 int 形式的打包像素值,然后可以使用 Color(int, boolean)构建一个颜色对象,您可以从中提取 RGBA 值,例如...

private static int[][][] getPixels(BufferedImage image) {
    int[][][] result = new int[height][width][4];
    for (int x = 0; x < image.getWidth(); x++) {
        for (int y = 0; y < image.getHeight(); y++) {
            Color c = new Color(image.getRGB(i, j), true);
            result[y][x][0] = c.getRed();
            result[y][x][1] = c.getGreen();
            result[y][x][2] = c.getBlue();
            result[y][x][3] = c.getAlpha();
        }
    }
}

这不是最有效的方法,但它是最简单的方法之一

关于Java:从缓冲图像中获取 RGBA 作为整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30856665/

相关文章:

javascript - React Js - 以动态方式渲染 Lightbox 组件的问题

C 错误 : conflicting types for function and previous declaration was here (not duplicate)

arrays - 为什么数组是不变的,而列表是协变的?

python - 如何读取 RGB 10 位原始图像?

javascript - 位图到 svg 路径

c# - 是否可以从深度位图中仅提取玩家的深度像素?

java - 如何使用 Java 生成 SAML 安全 SOAP 请求并使用 SAAJ 调用永恒的 Web 服务

java - Java中BigDecimal转Double时什么时候出现 "data loss"

java - 实例化缓冲编写器的差异

java - 由于 For 循环中的堆内存而导致内存不足?