【C#/WPF】Bitmap、BitmapImage、ImageSource 、byte[]转换问题
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[]转换问题的更多相关文章
- WPF Bitmap转Imagesource
var imgsource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(),IntPtr ...
- Wpf ImageSource对象与Bitmap对象的互相转换
原文:Wpf ImageSource对象与Bitmap对象的互相转换 Bitmap to ImageSource 将得到的Bitmap对象转换为wpf常用的Imagesource对象 BitmapSo ...
- Bitmap 与ImageSource之间的转换
public class ImageConverter { [DllImport("gdi32.dll", SetLastError = true)] private static ...
- WPF中实现图片文件转换成Visual对象,Viewport3D对象转换成图片
原文:WPF中实现图片文件转换成Visual对象,Viewport3D对象转换成图片 1.图片文件转换成Visual对象 private Visual CreateVisual(string imag ...
- WriteableBitmap/BitmapImage/MemoryStream/byte[]相互转换
1 WriteableBitmap/BitmapImage/MemoryStream/byte[]相互转换 2012-12-18 17:27:04| 分类: Windows Phone 8|字号 订 ...
- [转]WPF的BitmapImage的文件无法释放及内存泄露的问题
相信用过WPF的BitmapImage的,都在用类似这样的代码来解决文件无法删除的问题! 如果看看msdn上简单的描述,可以看到这样的说明: 如果 StreamSource 和 UriSource 均 ...
- java byte数组与int,long,short,byte转换
public class DataTypeChangeHelper { /** * 将一个单字节的byte转换成32位的int * * @param b * byte * @return conver ...
- Stream与byte转换
将 Stream 转成 byte[] /// <summary> /// 将 Stream 转成 byte[] /// </summary> public byte[] Str ...
- VSTO学习笔记(七)基于WPF的Excel分析、转换小程序
原文:VSTO学习笔记(七)基于WPF的Excel分析.转换小程序 近期因为工作的需要,要批量处理Excel文件,于是写了一个小程序,来提升工作效率. 小程序的功能是对Excel进行一些分析.验证,然 ...
随机推荐
- 微信小程序信息展示
概述 使用第三方在线API模拟数据,进行微信小程序开发.不会后端开发也可以体验微信小程序. 详细 代码下载:http://www.demodashi.com/demo/10719.html 一.准备工 ...
- ListView中Button事件
为了解决ListView中Item里的Button独立事件响应,能够採用下面方法: 在BaseAdapter的getview里加入加粗代码: <span style="font-siz ...
- Javascript中的数据类型知多少
JavaScript 是一种弱类型或者说动态语言.这意味着你不用提前声明变量的类型,在程序运行过程中,类型会被自动确定.这也意味着你可以使用同一个变量保存不同类型的数据 根据ECMAScript 5. ...
- 利用Windows 2003系统中实现两个网段的路由
利用Windows 2003系统中实现两个网段的路由 当一个局域网中存在两个以上网段时,分属于不同网段内的主机彼此互不可见.为了解决这个问 题,就必须在不同的网段之间设置路由器.如果花费上万元资金购买 ...
- 编译 boost
不想深究,只是可以编译出想要的lib文件 1.打开visual studio 2012 命令提示 2.进入 boost目录 3.运行booststrp.bat得到b2.exe.bjam.exe.pro ...
- Android清空Fragment回退栈
啊= =:国内的资料为什么都是抄来抄去的. 最后上了Stack Overflow才找到了正解. FragmentManager fragmentManager = getFragmentManager ...
- Orm框架开发之NewExpression合并问题
之前都是看别人写博客,自己没有写博客的习惯.在工作的过程中,总是会碰到许多的技术问题.有很多时候想记录下来,后面一直有许多的问题等着解决.总想着等系统完成了,再回头总结下.往往结果就把这事抛到脑后了. ...
- 什么是BGP线路?什么是BGP机房?
BGP(Border Gateway Protocol,边界网关协议)主要用于互联网AS(自治系统)之间的互联.BGP的最主要功能在于控制路由的传播和选择最好的路由.BGP是Internetproje ...
- unity, Find References In Scene
材质,脚本,shader等都可以通过Find References In Scene查看引用情况,如图. 当对一个文件点击Find References In Scene后,搜索命令会显示到Scene ...
- HDU 2444 The Accomodation of Students二分图判定和匈牙利算法
本题就是先推断能否够组成二分图,然后用匈牙利算法求出最大匹配. 究竟怎样学习一种新算法呢? 我也不知道什么方法是最佳的了,由于看书本和大牛们写的匈牙利算法具体分析,看了几乎相同两个小时没看懂,最后自己 ...