Java:从缓冲图像中获取 RGBA 作为整数数组 [英] Java: Get the RGBA from a Buffered Image as an Array of Integer

查看:27
本文介绍了Java:从缓冲图像中获取 RGBA 作为整数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Given an image file, say of PNG format, how to I get an array of int [r,g,b,a] representing the pixel located at row i, column j?

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

So far I am starting here:

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 值,例如...

You need to get the packed pixel value as an int, you can then use Color(int, boolean) to build a color object from which you can extract the RGBA values, for example...

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();
        }
    }
}

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

It's not the most efficient method, but it is one of the simplest

这篇关于Java:从缓冲图像中获取 RGBA 作为整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆