简体   繁体   中英

Convert byte[] to Bitmap in Core 2.1

I had a project working well in .Net 4.6.2, which makes heavy usage of converting byte[] to Bitmap.

public static Bitmap ByteArrayToImage(byte[] source)
    {
        TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
        return (Bitmap)tc.ConvertFrom(source);
    }

However, I have since upgraded projects to .Net Core 2.1 and this no longer works. I've read, and a few people have issues, but battling to find a fix.

TypeConverter cannot convert from System.Byte[]

Is there a way in 2.1 to achieve this conversion? It looks like https://github.com/SixLabors/ImageSharp might work, but when I search for it in Nuget, I get no results.

You'll need to put the bytes into a MemoryStream

public static Bitmap ByteArrayToImage(byte[] source)
{
    using (var ms = new MemoryStream(source))
    {
        return new Bitmap(ms);
    }
}

The code above will use the Bitmap(Stream stream) constructor.

Is there a way in 2.1 to achieve this conversion? It looks like https://github.com/SixLabors/ImageSharp might work, but when I search for it in Nuget, I get no results.

Yes, you can use this open source for your problem, but you can't get it via nuget. At the moment, you need MyGet to get that package. You can refer this link to know how to use ImageSharp packages: https://blogs.msdn.microsoft.com/dotnet/2017/01/19/net-core-image-processing/

Otherwise, you can convert your byte array to MemoryStream first:

    public static Bitmap ByteArrayToImage(byte[] source)
    {
        return new Bitmap(new MemoryStream(source));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM