Question

I am trying re-create an image using given 2D pixel arrays (rows, and columns) using the setRGB() method in BufferedImage.

Below is the follwing code:

BufferedImage bufferedImage = new BufferedImage(reconstructedJPEG[0].length, reconstructedJPEG.length, BufferedImage.TYPE_INT_RGB);
//loop through redPixels[][] array
for(int row=0; row<redPixels.length; row++){
    for(int col=0; col<redPixels[0].length; col++){
        //call setRGB() on redPixels
        bufferedImage.setRGB(col, row, (redPixels[row][col]));
    }
}

The code above works, but I am not sure how I can also set the green and blue pixel arrays? Right now, its a very dull, dark red/purple image, that does no look like the original image.

Also, is there a another away I can form these arrays into a 1D image (which would be its raw pixels, red+green+blue components into one integer?

Thanks any help would be great.

Was it helpful?

Solution

Combine the individual color values for the 3 channels (red, green and blue) in one pixel using bitwise operators:

int rgb = (redValue & 0xff) << 16 | (greenValue & 0xff) << 8 | (blueValue & 0xff);

Then call setRGB with the composed value as parameter:

bufferedImage.setRGB(col, row, rgb);

The bitwise operation sentence can be cumbersome at first sight but it does the following:

  • Take every channel value and make it 8-bit range based value (0, 255) using the & 0xff mask (the format BufferedImage.TYPE_INT_RGB expects channels to be 8-bit values)

    redValue & 0xff, greenValue & 0xff, blueValue & 0xff

  • Accommodates the channel values packing then into one 32 bit integer using the following layout:

    enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top