Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Image<Rgba32> to Byte[] using ImageSharp

Tags:

imagesharp

How can I convert an image to array of bytes using ImageSharp library?

Can ImageSharp library also suggest/provide RotateMode and FlipMode based on EXIF Orientation?

like image 328
dudedev Avatar asked Apr 25 '18 15:04

dudedev


2 Answers

If you are looking to convert the raw pixels into a byte[] you do the following.

var bytes = image.SavePixelData()

If you are looking to convert the encoded stream as a byte[] (which I suspect is what you are looking for). You do this.

using (var ms = new MemoryStream())
{
    image.Save(ms, imageFormat);
    return ms.ToArray();
}
like image 77
James South Avatar answered Oct 05 '22 14:10

James South


For those who look after 2020:

SixLabors seems to like change in naming and adding abstraction layers, so... Now to get a raw byte data you do the following steps.

  1. Get MemoryGroup of an image using GetPixelMemoryGroup() method.
  2. Converting it into array (because GetPixelMemoryGroup() returns a interface) and taking first element (if somebody tells me why they did that, i'll appreciate).
  3. From System.Memory<TPixel> get a Span and then do stuff in old way. (i prefer solution from @Majid comment)

So the code looks something line this:

var _IMemoryGroup = image.GetPixelMemoryGroup();
var _MemoryGroup = _IMemoryGroup.ToArray()[0];
var PixelData = MemoryMarshal.AsBytes(_MemoryGroup.Span).ToArray();

ofc you don't have to split this into variables and you can do this in one line of code. I did it just for clarification purposes. This solution only viable as for 06 Sep 2020

like image 24
ZecosMAX Avatar answered Oct 05 '22 15:10

ZecosMAX