C# 使用内存流将二进制转换为位图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13913353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:04:46  来源:igfitidea点击:

convert binary to bitmap using memory stream

c#.net

提问by heavy

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 .

嗨,我想将二进制数组转换为位图并在picturebox. 我编写了以下代码,但出现异常,提示参数无效。

  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;

    }

采纳答案by Thorsten Dittmar

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.

这真的取决于blob. 它是否是有效的位图格式(如 PNG、BMP、GIF 等?)。如果是位图中像素的原始字节信息,则不能这样做。

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

mStream.Seek(0, SeekOrigin.Begin)在 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;
    }
}

回答by juharr

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

不要处理 MemoryStream。它现在属于图像对象,将在您处理图像时处理。

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.

回答by Uthistran Selvaraj

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....

尝试这个。如果您仍然收到任何错误或异常;请发布您要转换为图像的字节。你的图像流应该有问题....