I need to display an image in a WPF application written in C#. The image content is generated by an external unmanaged library, which allocates the raster buffer itself.
I am trying to wrap that buffer in a BitmapSource object (attached as the Source of an Image control) using the Create method, but the method takes a byte array whereas all I have is an IntPtr to the buffer.
Is there a way to create a byte array from an unmanaged buffer ? Preferably without copying ? (I know that what I am doing is unsafe, but the buffer is guaranteed to persist for the whole lifetime of the application).
Or is there an alternative way to display a raster image from an unmanaged buffer into an Image or Canvas object or similar ?
Update:
I just missed that there is an overload of BitmapSource.Create that takes an IntPtr ! (Though I don’t know if that copies the image or not.)
>Solution :
In order to create a BitmapSource from an unmanaged raw pixel buffer, use the BitmapSource.Create method, e.g. like this:
PixelFormat format = PixelFormats.Bgr24;
int width = 768;
int height = 576;
int stride = (width * format.BitsPerPixel + 7) / 8;
int size = stride * height;
IntPtr buffer = ...
BitmapSource bitmap = BitmapSource.Create(
width, height, 96, 96, format, null, buffer, size, stride);