convert binary to bitmap using memory stream

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.

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

Tags:

C#

.Net