Bitmap转换为byte[]
private byte[] BitmapToBytes(Bitmap bitmap)
{
// 1.先将BitMap转成内存流
MemoryStream ms = new MemoryStream();
bitmap.Save(ms, ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
// 2.再将内存流转成byte[]并返回
byte[] bytes = new byte[ms.Length];
ms.Read(bytes, 0, bytes.Length);
ms.Dispose();
return bytes;
}
byte[]转换为Bitmap
private System.Drawing.Bitmap BytesToBitmap(byte[] Bytes)
{
MemoryStream stream = null;
try
{
stream = new MemoryStream(Bytes);
return new System.Drawing.Bitmap((System.Drawing.Image)new System.Drawing.Bitmap(stream));
}
catch (ArgumentNullException ex)
{
throw ex;
}
catch (ArgumentException ex)
{
throw ex;
}
finally
{
stream.Close();
}
}
在查阅如何转换的时候被坑了,下面是错误的byte[]转换为Bitmap
private System.Drawing.Bitmap ByteToBitmap(byte[] bytes)
{
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
System.Drawing.Bitmap bitmap = (System.Drawing.Bitmap)System.Drawing.Image.FromStream(ms);
ms.close();
return bitmap;
}
使用此代码转换时无法Save图像