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.

4
  • 4
    I'd probably just create a MemoryStream from the byte array, and then create a Btitmap from the stream. Commented Sep 11, 2018 at 8:16
  • 3
    using (MemoryStream ms = new MemoryStream(source)) {return new Bitmap(ms);} Commented Sep 11, 2018 at 8:27
  • Thanks guys. That worked. If you put an answer, I can mark it done. Nice one, thanks. Commented Sep 11, 2018 at 8:34
  • Possible duplicate of Byte Array to Image Conversion Commented Sep 11, 2018 at 8:58

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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));
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.