net-vips icon indicating copy to clipboard operation
net-vips copied to clipboard

Expose IntPtr-based overload for NewFromMemory()

Open jeffska opened this issue 1 year ago • 2 comments

It would be useful to have an overload for NewFromMemory() that takes an IntPtr instead of a byte[] for cases where we want to wrap existing unmanaged memory with a NetVips.Image, without having to do an allocate+copy. Somewhat similar to what's provided by NewFromMemoryCopy().

I've got a workaround by reflecting into some internal methods, but it would be nice to have this in an exposed API.

I'm happy to submit a PR.

jeffska avatar Aug 17 '22 00:08 jeffska

Indeed, it's currently missing a IntPtr-based overload for both Image.NewFromMemory() and Source.NewFromMemory() functions. I assume you wanted to do something like this?:

// Avoid reusing the image after subsequent use
Cache.Max = 0;

const int sizeInBytes = 100;
var memory = Marshal.AllocHGlobal(sizeInBytes);

// Zero the memory
Unsafe.InitBlockUnaligned((byte*)memory, 0, sizeInBytes); 

using (var im = Image.NewFromMemory(memory, sizeInBytes, 10, 10, 1, Enums.BandFormat.Uchar))
{
    im.OnPostClose += () => Marshal.FreeHGlobal(memory);
    im.WriteToFile("black-10x10.png");
} // OnPostClose

Let's tag this as an enhancement. Very happy to accept a PR, if you're able.

kleisauke avatar Aug 18 '22 11:08 kleisauke

Yes, that's essentially it. If I get some time this week, I'll try to put a PR together.

jeffska avatar Aug 21 '22 14:08 jeffska

Implemented with commit ea65d8e1129772664eb4aa5b7162e02814f1b6a5, this will be included as part of v2.3.0. Thanks for reporting this!

(I skipped this for Source.NewFromMemory() as it probably doesn't make sense to add a IntPtr-based overload for that)

kleisauke avatar Nov 25 '22 18:11 kleisauke

NetVips v2.3.0 is now available.

kleisauke avatar Mar 24 '23 13:03 kleisauke