Tuesday, June 4, 2019

ImageSharp: convert Image to byte array

See also on GitHub Gist

namespace Vurdalakov
{
    using System;
    using System.IO;
    using SixLabors.ImageSharp;
    using SixLabors.ImageSharp.Advanced;
    using SixLabors.ImageSharp.Formats;
    using SixLabors.ImageSharp.PixelFormats;

    public static class ImageSharpExtensions
    {
        public static Byte[] ToArray<TPixel>(this Image<TPixel> image, IImageFormat imageFormat) where TPixel : struct, IPixel<TPixel>
        {
            using (var memoryStream = new MemoryStream())
            {
                var imageEncoder = image.GetConfiguration().ImageFormatsManager.FindEncoder(imageFormat);
                image.Save(memoryStream, imageEncoder);
                return memoryStream.ToArray();
            }
        }
    }
}

Usage example:

var image = Image.Load<Rgba32>("c:\\temp\\myimage.jpg");

var pngBytes = image.ToArray(PngFormat.Instance);

No comments:

Post a Comment