如何使用Java从RGB像素值创建有效图像 [英] How to create valid image from RGB pixel values using java

查看:341
本文介绍了如何使用Java从RGB像素值创建有效图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个2D数组,其中包含RGB值.我需要根据这些像素值创建一个有效的图像并将其保存.我在下面给出了2D数组.我想在我的项目中实现这一部分,所以请帮助我.谢谢.

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

推荐答案

您可以构建

  • 第三个字节(16-23)为红色,
  • 第二个字节(8-15)为绿色,并且
  • 第一个字节(7-0)为蓝色.
  • 您可以按以下方式获取像素 RGB 值:

    You can get the pixel RGB value as follows:

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

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

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

    这篇关于如何使用Java从RGB像素值创建有效图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆