嗨我想将二进制arrey转换为位图并在图片框中显示图像我写下面的代码,但我得到例外,它说参数无效.
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;
}
Run Code Online (Sandbox Code Playgroud)
Tho*_*mar 13
这真的取决于什么blob.它是一种有效的位图格式(如PNG,BMP,GIF等?).如果它是关于位图中像素的原始字节信息,则不能这样做.
mStream.Seek(0, SeekOrigin.Begin)在行之前使用它可以帮助将流回放到开头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;
}
}
Run Code Online (Sandbox Code Playgroud)
不要丢弃MemoryStream.它现在属于图像对象,在处理图像时将被处理.
也考虑这样做
var ms = new MemoryStream(blob);
var img = Image.FromStream(ms);
.....
img.Dispose(); //once you are done with the image.
Run Code Online (Sandbox Code Playgroud)