在图片框中显示三个字节数组

时间:2014-01-07 09:04:44

标签: c# image rgb picturebox

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

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

这三个数组不为空,每个数组都存储数据。

2 个答案:

答案 0 :(得分:0)

你的意思是:

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;

答案 1 :(得分:0)

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

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作为参数创建位图。如果操作正确,它应该避免不必要的数组边界检查,以及不必要的复制。

相关问题