博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【C#/WPF】Bitmap、BitmapImage、ImageSource 、byte[]转换问题
阅读量:7063 次
发布时间:2019-06-28

本文共 4758 字,大约阅读时间需要 15 分钟。

原文:

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

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

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

  • Bitmap和BitmapImage相互转换
  • 谷歌上搜关键字 C# WPF Convert Bitmap BitmapImage
// Bitmap --> BitmapImagepublic 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 --> Bitmappublic 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 --> BitmapImagepublic 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 --> BitmapImagepublic 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 --> Bitmappublic 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[] --> BitmapImagepublic 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;}

转载地址:http://tvnll.baihongyu.com/

你可能感兴趣的文章
各角色眼中的性能测试
查看>>
Citrix XenDesktop 引发的学案(四)-与“您的虚拟桌面”之间的连接失败,状态(1030)...
查看>>
mysql-5.6的GTID复制的实现
查看>>
6421B Lab10 网络文件和打印服务的配置与故障排除
查看>>
快速安装配置zabbix_agent端
查看>>
DNS服务的配置与管理(5) 配置转发器
查看>>
AIP(Azure 信息保护)之一:启用与激活服务
查看>>
一步步学WebSocket(3)WebSocket协议格式
查看>>
linux更新内核
查看>>
通过mdadm命令调用内核MD模块实现软Raid
查看>>
为RemoteApp的登录用户(域用户)添加输入法的方法
查看>>
分享Open-E DSS V7 应用系列十篇!
查看>>
分享Silverlight/Windows8/WPF/WP7/HTML5一周学习导读(5月6日-5月12日)
查看>>
javascript框架概览备忘
查看>>
产品与技术(人员)间的职责关系
查看>>
企业云桌面-13-为企业新建组织单位
查看>>
SystemCenter2012SP1实践(5)SCVMM管理HyperV
查看>>
Ext JS添加子组件的误区
查看>>
微软私有云分享(R2)27维护窗口的使用
查看>>
Mac 平台下功能强大的Shimo软件使用指南
查看>>