tags:

views:

76

answers:

1

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?

A: 

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:

var bmp = new Bitmap(width, height, 0, System.Drawing.Imaging.PixelFormat.Format32bppArgb, data);

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!

Danvil