Java: Get the RGBA from a Buffered Image as an Arr

2019-03-02 19:12发布

问题:

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....
}

Thanks in advance!

回答1:

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



回答2:

BufferedImages have a method called getRGB(int x, int y) which returns an int where each byte is the components of the pixel (alpha, red, green and blue). If you dont want to do the bitwise operators yourself you can use Colors.getRed/Green/Blue methods by creating a new instance of Java.awt.Color with the int from getRGB.

You can do this in a loop to fill the three-dimensional array.