15

Hi I wanna convert binary array to bitmap and show image in a picturebox. I wrote the following code but I got exception that says that the parameter is not valid .

  public static Bitmap ByteToImage(byte[] blob)
    {
        MemoryStream mStream = new MemoryStream();
        byte[] pData = blob;
        mStream.Write(pData, 0, Convert.ToInt32(pData.Length));
        Bitmap bm = new Bitmap(mStream);
        mStream.Dispose();
        return bm;

    }
Soleil
  • 6,404
  • 5
  • 41
  • 61
heavy
  • 439
  • 2
  • 5
  • 13

3 Answers3

20

It really depends on what is in blob. Is it a valid bitmap format (like PNG, BMP, GIF, etc?). If it is raw byte information about the pixels in the bitmap, you can not do it like that.

It may help to rewind the stream to the beginning using mStream.Seek(0, SeekOrigin.Begin) before the line Bitmap bm = new Bitmap(mStream);.

public static Bitmap ByteToImage(byte[] blob)
{
    using (MemoryStream mStream = new MemoryStream())
    {
         mStream.Write(blob, 0, blob.Length);
         mStream.Seek(0, SeekOrigin.Begin);

         Bitmap bm = new Bitmap(mStream);
         return bm;
    }
}
Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139
  • 1
    Please take a look at [this rejected edit](http://stackoverflow.com/review/suggested-edits/3181577). From the [msdn](http://msdn.microsoft.com/en-us/library/system.io.memorystream.seek.aspx) it looks like he is right. – gunr2171 Oct 21 '13 at 16:02
  • How can this work when the MS doc is clearly stating "You must keep the stream open for the lifetime of the Bitmap."? Source: https://learn.microsoft.com/en-us/dotnet/api/system.drawing.bitmap.-ctor?view=netframework-4.6.2#System_Drawing_Bitmap__ctor_System_IO_Stream_ Also, this answer does not work in my case, where I use the Image for Telerik Report. Here I get a rendering error when I dispose the stream. – this.myself Sep 15 '21 at 15:15
5

Don't dispose of the MemoryStream. It now belongs to the image object and will be disposed when you dispose the image.

Also consider doing it like this

var ms = new MemoryStream(blob);
var img = Image.FromStream(ms);
.....
img.Dispose(); //once you are done with the image.
juharr
  • 31,741
  • 4
  • 58
  • 93
0
System.IO.MemoryStream mStrm = new System.IO.MemoryStream(your byte array);
Image im = Image.FromStream(mStrm);
im.Save("image.bmp");

Try this. If you still get any error or exception; please post your bytes which you are trying to convert to image. There should be problem in your image stream....

Uthistran Selvaraj
  • 1,371
  • 1
  • 12
  • 31