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. .net连接MySQL的方法

    摘自:http://www.cnblogs.com/huayangmeng/archive/2011/04/06/2006866.html 最近要用C#做一个东西,连接之前项目的数据库(用MySQL建 ...

  2. leetcode719:直线上的第k近点对

    问题描述 给定数组a[N],可以确定C(N,2)个点对,也就确定了C(N,2)个距离,求这些距离中第k小的距离(k<C(N,2)). 思路 看到第k小.第k大这种问题,首先想到二分法. 把求值问 ...

  3. 使用git 将自己的本地文件git到github上面的完整过程

    1.  首先在github网站上新建一个仓库,复制仓库地址(HTTP形式或者SSH形式,后者利用SSH,在最后一步push 的时候可以不用输入用户名和密码). 2.  在本地某个你想要的(文件夹)目录 ...

  4. Linux命令-查看进程命令:pstree

    查看进程树,ps aux查看进程,如果进程太多看起来很不方便,可以使用pstree以树形方式显示正在运行的所有进程 pstree -p 查看进程树 还是太多了,可以使用管道符进行查找httpd(apa ...

  5. Python len() 方法

    描述 Python len() 方法返回对象(字符串.列表.元组.字典等)长度或项目个数. 语法 len() 方法语法: len(obj) 参数 obj -- 对象(字符串.列表.元组.字典等). 返 ...

  6. tomcat6的编译和导入myeclipse

    声明:近期在学习tomcat6的源代码,网上搜索了些相关的资料,并自己操作了下进行了对应的汇总.如今总结例如以下 本文目的:编译tomcat6源代码+导入tomcat6源代码到myeclipse 測试 ...

  7. git 录制简单实用好工具 LICEcap

    官网 https://www.cockos.com/licecap/ 界面如图: 录制效果如下:

  8. html中一些常用标签及属性

    html中标签分为块级标签和行级标签 块级标签常用的有 <div> <p> <h1><hr><pre><table><ul ...

  9. Android开发3——查看和输出日志信息

    一.错误级别 Error > Warn > Info > Debug > Verbose(冗余) 二.Android项目日志查看视图 Console视图只能看项目的部署到模拟器 ...

  10. POJ 2553 The Bottom of Graph 强连通图题解

    Description We will use the following (standard) definitions from graph theory. Let V be a nonempty ...