如何使用java从RGB像素值创建有效的图像

时间:2023-02-01 22:22:42

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.

我有一个包含RGB值的2D数组。我需要从这些像素值创建一个有效的图像并保存它。我已经给出了下面的2D数组。我想在我的项目中实施这部分,请帮忙谢谢你!

         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 个解决方案

#1


4  

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

您可以构建BufferedImage类型为BufferedImage.TYPE_INT_RGB。此类型表示作为int类型的颜色,其中:

  • 3rd byte (16-23) is red,
  • 第3字节(16-23)为红色,
  • 2nd byte (8-15) is green and
  • 第二个字节(8-15)是绿色的
  • 1st byte (7-0) is blue.
  • 第一个字节(7-0)是蓝色的。

You can get the pixel RGB value as follows:

可以得到像素RGB值如下:

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

Example (Ideone full example code):

示例(Ideone完整示例代码):

  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);

#1


4  

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

您可以构建BufferedImage类型为BufferedImage.TYPE_INT_RGB。此类型表示作为int类型的颜色,其中:

  • 3rd byte (16-23) is red,
  • 第3字节(16-23)为红色,
  • 2nd byte (8-15) is green and
  • 第二个字节(8-15)是绿色的
  • 1st byte (7-0) is blue.
  • 第一个字节(7-0)是蓝色的。

You can get the pixel RGB value as follows:

可以得到像素RGB值如下:

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

Example (Ideone full example code):

示例(Ideone完整示例代码):

  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);