给定一个图像文件,例如 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/