没事总结一下平时用到的几种图像相互转换方法。供大家参考。
1.Bitmap 转byte[]数组:
/// <summary>
/// 将BitMap转换成bytes数组
/// </summary>
/// <param name="bitmap">要转换的图像</param>
/// <returns></returns>
private byte[] BitmapToByte(System.Drawing.Bitmap bitmap)
{
// 1.先将BitMap转成内存流
System.IO.MemoryStream ms = new System.IO.MemoryStream();
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
ms.Seek(0,System.IO.SeekOrigin.Begin);
// 2.再将内存流转成byte[]并返回
byte[] bytes = new byte[ms.Length];
ms.Read(bytes, 0, bytes.Length);
ms.Dispose();
return bytes;
}
2.byte[]转BitMap(这个是网上大多数人写的方法,实际上这个方法是有问题的。如果用该方法返回的Bitmap对象执行bitmap.Save()方法时会报错,那么多人也不验证就在上边写!!!,不说了,这个是反面教材,不要看。)
/// <summary>
/// Byte数组转Bitmap
/// </summary>
/// <param name="bytes">图像数组</param>
/// <returns></returns>
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;
}
// 该转换方法有问题,参考下边的正确转换方法
这个才是正确的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();
}
}
3.从image控件获取Bitmap
private Bitmap GetBitmap(System.Windows.Controls.Image image)
{
BitmapSource m = (BitmapSource)image.Source;
Bitmap bitmap = new System.Drawing.Bitmap(m.PixelWidth, m.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
Graphics graph = Graphics.FromImage(bitmap);
System.Drawing.Imaging.BitmapData data = bitmap.LockBits(
new System.Drawing.Rectangle(System.Drawing.Point.Empty, bitmap.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
m.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
bitmap.UnlockBits(data);
graph.DrawImage(bitmap, 0, 0);
return bitmap;
}
4.Bitmap转BitmapImage
public static BitmapImage ToBitmapImage(System.Drawing.Bitmap ImageOriginal)
{
System.Drawing.Bitmap ImageOriginalBase = new System.Drawing.Bitmap(ImageOriginal);
BitmapImage bitmapImage = new BitmapImage();
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
ImageOriginalBase.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
bitmapImage.BeginInit();
bitmapImage.StreamSource = ms;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
bitmapImage.Freeze();
}
return bitmapImage;
}
5.从文件打开图片,然后转成流,最后显示在控件上。这种好处是打开的文件不被占用,可以删除。直接打开的图片不可以删除。