Search code examples
c#.netimageimagesharp

How can I copy pixel data from an unmanaged buffer to an Image on ImageSharp?


I have an image buffer that lives in the unmanaged heap and I want to manipulate it with ImageSharp.

Right now I'm copying the unmanaged buffer into a byte array and then calling Image.LoadPixelData() which copies the buffer again into the image PixelBuffer.

How can I do a single copy instead? My image is in Argb32 format.


Solution

  • After some help from Anton Firsov on the ImageSharp gitter, I could do what I wanted. I needed to use DangerousGetPinnableReferenceToPixelBuffer():

    using(var image  = new Image<Argb32>(surfaceLock.Width, surfaceLock.Height))
    using(var output = new MemoryStream()) {
        unsafe {
            fixed(void* buffer = &image.DangerousGetPinnableReferenceToPixelBuffer()) {
                memcpy((IntPtr)buffer, surfaceLock.Buffer, surfaceLock.SlicePitchInBytes);
            }
        }
        image.Save(output, jpegEncoder);
        return output.ToArray();
    }