3

I have a 2D array which contains the RGB values. I need to create a valid image from these pixel values and save it. I have given the 2D array below. I wanted to implement this part in my project, so please help me with this. Thank you.

         int[] pixels = new int[imageSize * 3];
         int k = 0;
         for(int i=0; i<height; i++)
         {
            for(int j=0; j<width; j++)
            {
                if(k<imageSize*3)
               {
                    pixels[k] = r[i][j];
                    pixels[k+1] = g[i][j];
                    pixels[k+2] = b[i][j];
                }
               k = k+3;
            }
         }

1 Answer 1

8

You can build a BufferedImage of type BufferedImage.TYPE_INT_RGB. This type represents a color as an int where:

  • 3rd byte (16-23) is red,
  • 2nd byte (8-15) is green and
  • 1st byte (7-0) is blue.

You can get the pixel RGB value as follows:

int rgb = red;
rgb = (rgb << 8) + green; 
rgb = (rgb << 8) + blue;

Example (Ideone full example code):

  BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 

  for (int y = 0; y < height; y++) {
     for (int x = 0; x < width; x++) {
        int rgb = r[y][x];
        rgb = (rgb << 8) + g[y][x]; 
        rgb = (rgb << 8) + b[y][x];
        image.setRGB(x, y, rgb);
     }
  }

  File outputFile = new File("/output.bmp");
  ImageIO.write(image, "bmp", outputFile);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, i have seen similar answers along with a raster class along with your example, and I got confused as i am unaware of that class usage. But your answer is working even without raster class. Thanks a lot.

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.