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; // hereimage.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. Bitmap与byte[]转换

    一.Bitmap转换成byte[] 1.文件流的方式转换 ByteArrayOutputStream baos = new ByteArrayOutputStream(); mRBmp.compres ...

  2. Bitmap和YUV的转换

    以前做过的一个视频通话中,有用到Bitmap和YUV的转换,现在整理出来. 参考自:http://blog.csdn.net/lancees/article/details/7686046 http: ...

  3. byte转换int时为何与0xff进行与运算

    2019独角兽企业重金招聘Python工程师标准>>> ava中byte转换int时为何与0xff进行与运算 在剖析该问题前请看如下代码 public static String b ...

  4. byte与或运算 java_java中byte转换int时为何与0xff进行与运算

    本文总结了java中byte转换int时总是与0xff进行与运算的原因. 在剖析该问题前请看如下代码: public static String bytes2HexString(byte[] b) { ...

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

    1 public class DataTypeChangeHelper { 2 /** 3 * 将一个单字节的byte转换成32位的int 4 * 5 * @param b 6 * byte 7 * ...

  6. C# 图片与byte[]转换

    图片与byte[]转换 希望对新学习C#的同学有帮助,代码如下! 图片 转为 byte[] private string ImgToBase64String(Image img){try{Binary ...

  7. Golang黑科技之——string与[]byte转换

    我们知道,相对于C语言,golang是类型安全的语言.但是安全的代价就是性能的妥协. 下面我们通过Golang中的"黑科技"来一窥Golang不想让我们看到的"秘密&qu ...

  8. 网络流量单位bps与系统单位byte转换 (转)

    注意读书法 网络流量单位bps与系统单位byte转换 何謂 bps ? bps 是 bits per second 的簡稱.一般資料機及網路通訊的傳輸速率都是以「bps」為單位.如14.4Kbps.2 ...

  9. 16进制和byte[]转换工具类

    package com.lyn.utils_library;/*** 16进制和byte[]转换工具类** @author longyn* @version 1.0.0*/ public class ...

最新文章

  1. 2017全球教育机器人行业研究报告(附PDF下载)
  2. [hdu4333]Revolving Digits
  3. MonoDroid相关资源
  4. css就近原则_细品100道CSS知识点(上)「干货满满」
  5. Bootstrap3 按钮组插件
  6. C结构体之位域(位段)
  7. 藏红花怎么推广?百度下拉词|抖音下拉词框|信息流推广-三剑合璧
  8. python字符串split()函数
  9. Apache Camel系列(3)----Redis组件
  10. 学习python-day1
  11. 计算机办公自动化知识试题及答案,2015年计算机办公自动化考试试题及答案
  12. 数据挖掘技术基本任务
  13. 写简历的大原则和投简历的小技巧
  14. 1003【顺序结构】A+B 问题
  15. 量化交易5-backtrader编写均线策略
  16. 金匮要略重点整理 笔记
  17. 水果店圈子:水果店坏水果应该怎么处理,水果店卖剩下的水果如何处理
  18. 高并发系统设计二十六(配置中心)
  19. 抽象类 枚举 反射 接口
  20. 洛谷 P1710 地铁涨价 (dfs+bfs)

热门文章

  1. 小米技术委员能扛起雷军技术立业的大旗吗?
  2. iOS银联支付(最新)
  3. pytorch LSTM的股价预测
  4. 2011年5月51CTO壁纸点评活动获奖名单【已结束】
  5. 计算机自带的配置检测,Win10如何使用系统自带的硬件设备检测工具?
  6. w7系统出现无法更新服务器,win7系统自动更新选项不能用了的解决方法
  7. 聊聊信任:衣服掉地上会脏的
  8. 微信小程序 —— 模块化方法的总结
  9. UI自动化测试面试题总结
  10. Unity技术分享之调用Youtu实现智能AI图像处理人脸识别,证照识别等