Convert binary files to bitmaps using memory stream

Hi, I want to convert arrey binary to bitmap and show image in picture. I am writing the following code, but I get an exception that it says that the parameter is invalid.

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; } 
+6
source share
4 answers

It really depends on what is in the blob . Is it a valid bitmap image format (e.g. PNG, BMP, GIF, etc.?). If this is raw byte information about the pixels in a bitmap, you cannot do so.

This can help rewind the stream with mStream.Seek(0, SeekOrigin.Begin) before the Bitmap bm = new Bitmap(mStream); string 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; } } 
+7
source

Do not delete MemoryStream. Now it belongs to the image object and will be deleted when the image is deleted.

Also think about how to do it.

 var ms = new MemoryStream(blob); var img = Image.FromStream(ms); ..... img.Dispose(); //once you are done with the image. 
+4
source
 System.IO.MemoryStream mStrm = new System.IO.MemoryStream(your byte array); Image im = Image.FromStream(mStrm); im.Save("image.bmp"); 

Try it. If you still get any error or exception; send your bytes that you are trying to convert to an image. There should be a problem in your image stream.

0
source

I'm not sure if these codes will work for you, but you can follow these instructions:

 byte[] pData = blob; MemoryStream ms = new MemoryStream(pData); return Bitmap.FromResource(ms); 

Bitmap.FromResource from MSDN;

Creates a bitmap from the specified Windows resource.

0
source

All Articles