convert binary to bitmap using memory stream

前端 未结 3 974
执念已碎
执念已碎 2020-12-10 04:19

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 val

相关标签:
3条回答
  • 2020-12-10 04:44

    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;
        }
    }
    
    0 讨论(0)
  • 2020-12-10 05:01
    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....

    0 讨论(0)
  • 2020-12-10 05:02

    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.
    
    0 讨论(0)
提交回复
热议问题