如何使用非托管数据设置位图?
我有 int width, height;
和 IntPtr data;
,它们来自非托管的 unsigned 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]));
}
}
有更直接的方法来复制数据吗?
I have int width, height;
and IntPtr data;
which comes from a unmanaged unsigned char* pointer and I would like to create a Bitmap to show the image data in a GUI. Please consider, that width
must not be a multiple of 4, i do not have a "stride" and my image data is aligned as BGRA.
The following code works:
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]));
}
}
Is there a more direct way to copy the data?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如我所发现的,pixelformat Format32bppArgb 使用请求的 BGRA 顺序(尽管有名称),并且在这种情况下步幅必须为 0。所以答案很简单:
需要注意的是,Bitmap 并不复制数据,而是直接使用给定的指针。因此,当位图仍然使用它时,一定不要在非托管世界中释放数据指针!
As I figured out, pixelformat Format32bppArgb uses the requested BGRA order (despite the name) and stride must be 0 in this case. So the answer is simply:
It should be noted, that Bitmap does not make a copy of data, but uses the given pointer directly. So one must not release the data pointer in the unmanaged world, while the Bitmap still uses it!