How to set up a Bitmap with unmanaged data?

Posted by Danvil on Stack Overflow See other posts from Stack Overflow or by Danvil
Published on 2010-04-15T16:43:13Z Indexed on 2010/04/15 19:13 UTC
Read the original article Hit count: 246

Filed under:

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?

© Stack Overflow or respective owner

Related posts about c#