Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用非托管数据设置位图?_C#_Bitmap - Fatal编程技术网

C# 如何使用非托管数据设置位图?

C# 如何使用非托管数据设置位图?,c#,bitmap,C#,Bitmap,我有int宽度、高度和IntPtr数据来自一个非托管的无符号char*指针,我想创建一个位图来在GUI中显示图像数据。请考虑,宽度< /代码>不能是4的倍数,我没有“步幅”,并且我的图像数据排列成BGRA。 以下代码起作用: byte[] pixels = new byte[4*width*height]; System.Runtime.InteropServices.Marshal.Copy(data, pixels, 0, pixels.Length); var bmp =

我有
int宽度、高度
IntPtr数据来自一个非托管的无符号char*指针,我想创建一个位图来在GUI中显示图像数据。请考虑,<代码>宽度< /代码>不能是4的倍数,我没有“步幅”,并且我的图像数据排列成BGRA。

以下代码起作用:

byte[] pixels = new byte[4*width*height];    
System.Runtime.InteropServices.Marshal.Copy(data, pixels, 0, pixels.Length);    
var bmp = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);   

for(int i=0; i<height; i++) {
  for(int j=0; j<width; j++) {
    int p = 4*(width*i + j);
    bmp.SetPixel(j, i, Color.FromArgb(pixels[p+3], pixels[p+2], pixels[p+1], pixels[p+0]));
  }
}
byte[]像素=新字节[4*宽度*高度];
System.Runtime.InteropServices.Marshal.Copy(数据,像素,0,像素,长度);
var bmp=新位图(宽度、高度、系统、绘图、成像、像素格式、格式32bppargb);

对于(int i=0;i,正如我所想,pixelformat 32bpParGB使用请求的BGRA顺序(不管名称如何),在这种情况下,步幅必须为0。因此答案很简单:

var bmp = new Bitmap(width, height, 0, System.Drawing.Imaging.PixelFormat.Format32bppArgb, data);
需要注意的是,位图不复制数据,而是直接使用给定的指针。因此,在非托管世界中,当位图仍在使用数据指针时,不能释放数据指针