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,red,green和blue)。 如果您不想自己执行按位运算符,可以使用Color.getRed / Green / Blue方法,通过使用getRGB中的int创建一个新的Java.awt.Color实例。

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