Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating an image from an unmanaged buffer

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading