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



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

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

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

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

BufferedImages有一个名为getRGB(int x,int y(的方法,它返回一个int,其中每个字节都是像素的组成部分(alpha,红色,绿色和蓝色(。如果你不想自己做按位运算符,你可以使用 Colors.getRed/Green/Blue 方法,使用 getRGB 中的 int 创建一个新的 Java.awt.Color 实例。

您可以在循环中执行此操作以填充三维数组。

这是我针对此问题的代码:

 File f = new File(filePath);//image path with image name like "lena.jpg"
 img = ImageIO.read(f);
 if (img==null) //if img null return
    return;
 //3d array [x][y][a,r,g,b]  
 int [][][]pixel3DArray= new int[img.getWidth()][img.getHeight()][4];
     for (int x = 0; x < img.getWidth(); x++) {
         for (int y = 0; y < img.getHeight(); y++) {
            int px = img.getRGB(x,y); //get pixel on x,y location
            //get alpha;
            pixel3DArray[x][y][0] =(px >> 24)& 0xff; //shift number and mask
            //get red
            pixel3DArray[x][y][1] =(px >> 16)& 0xff;

            //get green
            pixel3DArray[x][y][2] =(px >> 8)& 0xff;
            //get blue
            pixel3DArray[x][y][3] =(px >> 0)& 0xff;
         }
    }

最新更新