How to set up a Bitmap with unmanaged data?
- by Danvil
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?