Search code examples
javabufferedimage

java how to convert a int[][] to an BufferedImage


i have an 2D integer array, which i get from the BufferedImage method "getRGB()". when i try to convert the 2D integer array back to BufferdImage, i get only a black picture.

This method

BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix[0].length; j++) {
            int pixel=matrix[i][j];
            System.out.println("The pixel in Matrix: "+pixel);
            bufferedImage.setRGB(i, j, pixel);
            System.out.println("The pixel in BufferedImage: "+bufferedImage.getRGB(i, j));
        }
    }

give this output:

The pixel in Matrix: 0
The pixel in BufferedImage: -16777216
The pixel in Matrix: 721420288
The pixel in BufferedImage: -16777216
The pixel in Matrix: 738197504
The pixel in BufferedImage: -16777216
The pixel in Matrix: 520093696
The pixel in BufferedImage: -16777216
The pixel in Matrix: 503316480
The pixel in BufferedImage: -16777216

why is every Pixel "-16777216"?

Thanks!

UPDATE

the method which returns the integer Matrix

public int[][] getMatrixOfImage(BufferedImage bufferedImage) {
    int width = bufferedImage.getWidth(null);
    int height = bufferedImage.getHeight(null);
    int[][] pixels = new int[width][height];
    for (int i = 0; i < width; i++) {
        for (int j = 0; j < height; j++) {
            pixels[i][j] = bufferedImage.getRGB(i, j);
        }
    }

    return pixels;
}

Solution

  • All your pixels seem to be black with different alpha values. You have to use TYPE_INT_ARGB to not lose the alpha channel.