Image to byte array converter .NET Standard

PUBLISHED ON 15 DEC 2018 — .NET STANDARD

Converting an image to an array and back to an image is a very useful feature when for example saving images to a database.

.Net Framework offers a class ImageConverter for this. The problem is this class is not available in System.Drawing.Common, the package we need to work with images in .Net Standard.

We still can write our own converter very easily using a Stream.

Here is an example of such a converter using a MemoryStream

public static class ImageConverter
{
    public static byte[] ToByteArray(Image image)
    {
        using (var ms = new MemoryStream())
        {
            image.Save(ms, image.RawFormat);
            return ms.ToArray();
        }
    }

    public static Image ToImage(byte[] imageBytes)
    {
        using (var ms = new MemoryStream(imageBytes))
        {
            return Image.FromStream(ms);
        }
    }
}

Like said above, for it to work we need to install the Nuget package System.Drawing.Common, which contains the Image class.

comments powered by Disqus