C#/WPF项目中,用到图像相关的功能时,涉及到多种图像数据类型的相互转换问题,这里做了个整理。包含的内容如下:

  • Bitmap和BitmapImage相互转换。
  • RenderTargetBitmap –> BitmapImage
  • ImageSource –> Bitmap
  • BitmapImage和byte[]相互转换。
  • byte[] –> Bitmap

StackOverflow上有很多解决方案,这里选择了试过可行的方法:

  • Bitmap和BitmapImage相互转换
  • 谷歌上搜关键字 C# WPF Convert Bitmap BitmapImage
// Bitmap --> BitmapImage
public static BitmapImage BitmapToBitmapImage(Bitmap bitmap)
{
using (MemoryStream stream = new MemoryStream())
{
bitmap.Save(stream, ImageFormat.Png); // 坑点:格式选Bmp时,不带透明度 stream.Position = 0;
BitmapImage result = new BitmapImage();
result.BeginInit();
// According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed."
// Force the bitmap to load right now so we can dispose the stream.
result.CacheOption = BitmapCacheOption.OnLoad;
result.StreamSource = stream;
result.EndInit();
result.Freeze();
return result;
}
} // BitmapImage --> Bitmap
public static Bitmap BitmapImageToBitmap(BitmapImage bitmapImage)
{
// BitmapImage bitmapImage = new BitmapImage(new Uri("../Images/test.png", UriKind.Relative)); using (MemoryStream outStream = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bitmapImage));
enc.Save(outStream);
Bitmap bitmap = new Bitmap(outStream); return new Bitmap(bitmap);
}
}
  • RenderTargetBitmap –> BitmapImage
// RenderTargetBitmap --> BitmapImage
public static BitmapImage ConvertRenderTargetBitmapToBitmapImage(RenderTargetBitmap wbm)
{
BitmapImage bmp = new BitmapImage();
using (MemoryStream stream = new MemoryStream())
{
BmpBitmapEncoder encoder = new BmpBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(wbm));
encoder.Save(stream);
bmp.BeginInit();
bmp.CacheOption = BitmapCacheOption.OnLoad;
bmp.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
bmp.StreamSource = new MemoryStream(stream.ToArray()); //stream;
bmp.EndInit();
bmp.Freeze();
}
return bmp;
} // RenderTargetBitmap --> BitmapImage
public static BitmapImage RenderTargetBitmapToBitmapImage(RenderTargetBitmap rtb)
{
var renderTargetBitmap = rtb;
var bitmapImage = new BitmapImage();
var bitmapEncoder = new PngBitmapEncoder();
bitmapEncoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap)); using (var stream = new MemoryStream())
{
bitmapEncoder.Save(stream);
stream.Seek(0, SeekOrigin.Begin); bitmapImage.BeginInit();
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.StreamSource = stream;
bitmapImage.EndInit();
} return bitmapImage;
}
  • ImageSource –> Bitmap
// ImageSource --> Bitmap
public static System.Drawing.Bitmap ImageSourceToBitmap(ImageSource imageSource)
{
BitmapSource m = (BitmapSource)imageSource; System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(m.PixelWidth, m.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); // 坑点:选Format32bppRgb将不带透明度 System.Drawing.Imaging.BitmapData data = bmp.LockBits(
new System.Drawing.Rectangle(System.Drawing.Point.Empty, bmp.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); m.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
bmp.UnlockBits(data); return bmp;
}
  • BitmapImage和byte[]相互转换
// BitmapImage --> byte[]
public static byte[] BitmapImageToByteArray(BitmapImage bmp)
{
byte[] bytearray = null;
try
{
Stream smarket = bmp.StreamSource; ;
if (smarket != null && smarket.Length > 0)
{
//设置当前位置
smarket.Position = 0;
using (BinaryReader br = new BinaryReader(smarket))
{
bytearray = br.ReadBytes((int)smarket.Length);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return bytearray;
} // byte[] --> BitmapImage
public static BitmapImage ByteArrayToBitmapImage(byte[] array)
{
using (var ms = new System.IO.MemoryStream(array))
{
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad; // here
image.StreamSource = ms;
image.EndInit();
image.Freeze();
return image;
}
}
  • byte[] –> Bitmap
public static System.Drawing.Bitmap ConvertByteArrayToBitmap(byte[] bytes)
{
System.Drawing.Bitmap img = null;
try
{
if (bytes != null && bytes.Length != 0)
{
MemoryStream ms = new MemoryStream(bytes);
img = new System.Drawing.Bitmap(ms);
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return img;
}

【C#/WPF】Bitmap、BitmapImage、ImageSource 、byte[]转换问题的更多相关文章

  1. WPF Bitmap转Imagesource

    var imgsource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(),IntPtr ...

  2. Wpf ImageSource对象与Bitmap对象的互相转换

    原文:Wpf ImageSource对象与Bitmap对象的互相转换 Bitmap to ImageSource 将得到的Bitmap对象转换为wpf常用的Imagesource对象 BitmapSo ...

  3. Bitmap 与ImageSource之间的转换

    public class ImageConverter { [DllImport("gdi32.dll", SetLastError = true)] private static ...

  4. WPF中实现图片文件转换成Visual对象,Viewport3D对象转换成图片

    原文:WPF中实现图片文件转换成Visual对象,Viewport3D对象转换成图片 1.图片文件转换成Visual对象 private Visual CreateVisual(string imag ...

  5. WriteableBitmap/BitmapImage/MemoryStream/byte[]相互转换

    1 WriteableBitmap/BitmapImage/MemoryStream/byte[]相互转换 2012-12-18 17:27:04|  分类: Windows Phone 8|字号 订 ...

  6. [转]WPF的BitmapImage的文件无法释放及内存泄露的问题

    相信用过WPF的BitmapImage的,都在用类似这样的代码来解决文件无法删除的问题! 如果看看msdn上简单的描述,可以看到这样的说明: 如果 StreamSource 和 UriSource 均 ...

  7. java byte数组与int,long,short,byte转换

    public class DataTypeChangeHelper { /** * 将一个单字节的byte转换成32位的int * * @param b * byte * @return conver ...

  8. Stream与byte转换

    将 Stream 转成 byte[] /// <summary> /// 将 Stream 转成 byte[] /// </summary> public byte[] Str ...

  9. VSTO学习笔记(七)基于WPF的Excel分析、转换小程序

    原文:VSTO学习笔记(七)基于WPF的Excel分析.转换小程序 近期因为工作的需要,要批量处理Excel文件,于是写了一个小程序,来提升工作效率. 小程序的功能是对Excel进行一些分析.验证,然 ...

随机推荐

  1. 兼容火狐,ie8的 js urlencode和urldecode

    function UrlEncode(str)//url编码{ var i,temp,p,q; var result=""; for(i=0;i<str.length;i++ ...

  2. linux 常用awk命令

    linux awk命令详解awk是一个强大的文本分析工具,相对于grep的查找,sed的编辑,awk在其对数据分析并生成报告时,显得尤为强大.简单来说awk就是把文件逐行的读入,以空格为默认分隔符将每 ...

  3. HighCharts: 设置时间图x轴的宽度

    这个x轴宽度的设置整了好久,被老板催的要死 highcharts的api文档很难找,找了半天也没找到,网上资料少,说的试了下,也没有,我用的图里api文档里没有介绍,这个属性不知道的话,根本不好找.为 ...

  4. js常用点

    <span onClick="onDetail(this.id,'edit');"  style="cursor: hand;color:black;" ...

  5. HDU 1517 A Multiplication Game (博弈)

    A Multiplication Game Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Ot ...

  6. FA_手工明细增加固定资产(流程)

    2014-06-08 Created By BaoXinjian

  7. Ibatis基础知识:#与$的差别

    背景 Ibatis是一个轻量级.非侵入式的持久层框架,适用于范围较广.较轻便--当然,不管J2EE中哪一个持久层框架,都会基于JDBC(不细究JNDI方式).我们在SqlMap中编写SQL,利用各种S ...

  8. MPU6050读取FIFI数据时mpu_dmp_get_data的返回值一直是1

    试验中发现:不断进行循环读fiffo就可以得到正常数据.形如这样 );//返回值:0,DMP成功解出欧拉角 printf("pitch=%f\troll=%f\tyaw=%f\r\n&quo ...

  9. mysql (已解决)Access denied for user 'root'@'localhost' (using password: NO)

    找到mysql中的my.ini,在最后一行加入 skip-grant-tables 在“管理工具”-”服务” 中重启mysql 解决问题

  10. jquery插件Flot的简单讲解

    只是说一下基本用法,举一两个例子,详细用法请查看官方文档 使用方法是要先引入jquery插件,然后引入flot插件. <script type="text/javascript&quo ...