Imagesharp: Creating a new Image<TPixel> by Wrapping Memory<byte>

Created on 29 Jan 2020  路  2Comments  路  Source: SixLabors/ImageSharp

As discussed in gitter:

With the current API, it is possible to create a new image in two ways:

  • LoadPixelData: which accepts a Span , but it makes an internal copy of the source data.
  • WrapMemory: which requires a Memory to wrap user memory.

The problem is that in many cases, the source data is provided as a plain byte array. this is specially true when dealing with devices at low level, like cameras and sensors.

In these cases, it would be desirable to do have Image,WrapPixelData(Byte[]) or something like that:

c# var bits = new Byte[256*256*4]; var image = Image<Argb32>.WrapPixelData(bits, 256, 256);

@antonfirsov unfortunately, MemoryMarshal can't cast Memory-s only Spans. There is no API for what you want, but you can implement a MemoryManager which does the span-casting on it's API surface. Feel free to raise a feature request so we remember to add this later.

I am aware that with the current ImageSharp architecture this might be difficult, but I believe it's a case scenario that might show quite often, so if you guys can find a solution for this...

API enhancement feature request

Most helpful comment

I edited the title, since byte[] could be implicitly converted to Memory<byte> (same element type). We need to add the following method:

public class Image
{
+    public static Image<TPixel> WrapMemory(Memory<byte> memory, int width, int height);
}

All 2 comments

I edited the title, since byte[] could be implicitly converted to Memory<byte> (same element type). We need to add the following method:

public class Image
{
+    public static Image<TPixel> WrapMemory(Memory<byte> memory, int width, int height);
}
public class Image
{
+    public static Image<TPixel> WrapMemory(Memory<byte> memory, int width, int height);
}

Yes, that's exactly what I would need. But I'm wondering how would you implement it.

It's certainly non trivial to cast a Memory<byte> to a Memory<TPixel> and if there's an API for that I would gladly want to know...

So I pressume ImageSharp would need to do some work under the hood.

Was this page helpful?
0 / 5 - 0 ratings