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

问题描述:

我有一个包含RGB值的二维数组。我需要从这些像素值创建一个有效的图像并保存它。下面给出了二维数组。我想在我的项目中实现这个部分,所以请帮助我。谢谢。如何使用java创建RGB像素值的有效图像

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

你可以建立BufferedImage.TYPE_INT_RGB类型的BufferedImage。这种类型的代表色作为ìnt其中:

  • 第三字节(16-23)是红色,
  • 第二字节(8-15)是绿色和
  • 第一字节(7-0)是蓝色。

你可以得到的像素RGB值如下:

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

例(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); 
+0

太感谢你了,我有一个光栅类沿着看到了类似的答案用你的例子,我感到困惑,因为我不知道这个类的用法。但是即使没有光栅类,你的答案也可以工作。非常感谢。 – user3364490 2015-02-23 12:37:40