Home > Software design >  Creating an image from an unmanaged buffer
Creating an image from an unmanaged buffer

Time:04-25

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

CodePudding user response:

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

In case you want to cyclically update the Source of an Image element, it may may be more efficient to overwrite the buffer of a single WriteableBitmap instead of reassigning the Image's Source with a new BitmapSource in each cycle.

CodePudding user response:

I would suggest using a WriteableBitmap. While this do require a copy, it should not need any allocations, and I would expect the performance to be well within the requirements for a live view.

myWriteableBitmap.WritePixels(
    new Int32Rect(0, 0, width, height),
    bufferPointer,
    bufferSize,
    stride);
  • Related