【问题标题】:display three array of byte in picture box在图片框中显示三个字节数组
【发布时间】:2014-01-07 17:35:58
【问题描述】:

我有三个字节数组存储三种颜色(红、绿、蓝),如何在 c# 的图片框中显示这个数组,文件类型是图像的位图文件

byte[,] R=new byte[width, height];
byte[,] G=new byte[width, height];
byte[,] B=new byte[width, height];

这三个数组都不是空的,每个数组里都有数据。

【问题讨论】:

    标签: c# image rgb picturebox


    【解决方案1】:

    你的意思是:

    Bitmap bmp = new Bitmap(width,height);
    for(int i=0;i<width;i++)
    for(int j=0;j<height;j++) {
        SetPixel(i,j,Color.FromArgb(R[i,j],G[i,j],B[i,j]));
    }
    picturebox.image=bmp;
    

    【讨论】:

      【解决方案2】:

      您必须从数据中构建一个单字节数组,这不会很快,因为您必须交错数据。基本上,你会做这样的事情:

      var bytes= new byte[width * height * 4];
      
      for (var x = 0; x < width; x++)
        for (var y = 0; y < height; y ++)
        {
          bytes[(x + y * width) * 4 + 1] = R[x, y];
          bytes[(x + y * width) * 4 + 2] = G[x, y];
          bytes[(x + y * width) * 4 + 3] = B[x, y];
        }
      

      然后您可以使用字节数组创建位图,如下所示:

      var bmp = new Bitmap(width, height);
      
      var data = bmp.LockBits(new Rectangle(0, 0, width, height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb)
      
      Marshal.Copy(bytes, 0, data.Scan0, width * height * 4);
      
      bmp.UnlockBits(data);
      

      请注意,您应该确保始终调用bmp.UnlockBits,因此您应该将它放在 finally 块中。

      这不一定是最好或最快的方法,但这取决于您的需求:)

      如果您真的想要最快的方式,您可能会使用不安全的代码(不是因为它本身更快,而是因为 .NET 位图 不是本机管理的 - 它是非托管位图的托管包装器)。您将在非托管堆上为字节数组分配内存,然后使用以IntPtr scan0 作为参数的构造函数填充数据并创建位图。如果操作正确,应该避免不必要的数组边界检查,以及不必要的复制。

      【讨论】:

        猜你喜欢
        • 2014-07-21
        • 2011-01-21
        • 1970-01-01
        • 2016-02-11
        • 1970-01-01
        • 2014-12-11
        • 1970-01-01
        • 2021-03-25
        • 2012-08-05
        相关资源
        最近更新 更多