Pablo Montilla
Pablo Montilla

Reputation: 3050

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.

Upvotes: 0

Views: 2128

Answers (2)

Pablo Montilla
Pablo Montilla

Reputation: 3050

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

Upvotes: 2

Yuri S
Yuri S

Reputation: 5370

You could create UnmanagedMemoryStream and then Image.Load(stream)) but I am not sure if it is better than what you are doing now

Upvotes: 1

Related Questions