2

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

10 Comments

thanks for the reply. I initially split the pixels like so: rgbPixels[j][0] = ((rawPixels[j]>>16)&0xff); rgbPixels[j][1] = ((rawPixels[j]>>8)&0xff); rgbPixels[j][2] = (rawPixels[j]&0xff); rgbPixels[j][3] = ((rawPixels[j]>>24)&0xff); Should I leave out the alpha value?
Yes, the alpha channel should be empty (ignored, in fact) for this format.
Thanks for the reply. For some reason, my resultant image is completely scrambled up. I think it could be the fact i took in the alpha values initially, but did nothing with it, and now I am using the 3 RGB values only to form the image again. What should I do with that other array set, (i'd have to create a alpha array) ? Thanks
Unless I could alter the initial operations, and don't take in that alpha values. Thanks
Try ignoring the alpha and using: rgbPixels[j][0] << 16 | rgbPixels[j][1] << 8 | rgbPixels[j][2] only
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.