首页 > 编程语言 >【C#/WPF】Bitmap、BitmapImage、ImageSource 、byte[]转换问题

【C#/WPF】Bitmap、BitmapImage、ImageSource 、byte[]转换问题

时间:2023-12-21 15:45:57浏览次数:46  
标签:stream C# BitmapImage System Bitmap bmp new

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;
}
     

标签:stream,C#,BitmapImage,System,Bitmap,bmp,new
From: https://www.cnblogs.com/webenh/p/17919218.html

相关文章

  • Wpf Bitmap(Image)Base64,Url,文件Path,Stream转BitmapSource(ImageSource),无需外部d
    直接上代码usingSystem;usingSystem.Drawing;usingSystem.IO;usingSystem.Windows.Forms;usingSystem.Windows.Media.Imaging;namespaceCommonUtils{///<summary>///Windows图片处理///</summary>publicstaticclassWindowsImage......
  • Json.Net Deserialize a Collection from BSON
    DeserializeaCollectionfromBSON(newtonsoft.com)Thissamplesets ReadRootValueAsArray to true sotherootBSONvalueiscorrectlyreadasanarrayinsteadofanobjectanddeserializesBSONtoacollection.SampleTypesCopypublicclassEv......
  • 2002 - Can't connect to server on '54.xxx.xxx.xxx' (36)
    远程连接mysql数据库的时候显示Can'tconnecttoMySQLserver(10060)如下图所示可以从以下几个方面入手,找出错误的原因:1.网络问题网络不通时会导致这个问题检查下是不是能ping通2.mysql账户设置mysql账户是否不允许远程连接--mysql-uroot-p--showdataba......
  • 纯css展示loading加载动画
    https://uiverse.io/barisdogansutcu/light-rat-32<svgviewBox="25255050"><circler="20"cy="50"cx="50"></circle></svg>svg{width:3.25em;transform-origin:center;animation:rot......
  • Nacos未授权 CVE-2021-29441
    Nacos未授权CVE-2021-29441环境搭建环境dockerfile在文末环境启动docker-composeup-d查看下当前的容器dockerps漏洞复现访问Web页面127.0.0.1:8848抓包,访问http://127.0.0.1:8848/nacos/v1/auth/users?pageNo=1&pageSize=2将User-Agent的值修改为Nacos-Server......
  • docker初步入门学习安装redis和mysql
    dockerrun--namemyredis-p6379:6379-dredisredis-server--appendonlyyesdockerrun--namemysql-eMYSQL_ROOT_PASSWORD=123456-d-p3306:3306mysql:5.7.27dockerpullmysql:5.7.27dockerrun-d--hostnamemy-rabbit--namemyra......
  • [转]CryptoJS-中文文档
    原文地址:CryptoJS-中文文档-掘金原始文档:code.google.com/archive/p/c…介绍CryptoJS是一个JavaScript的加解密的工具包。它支持多种算法:MD5、SHA1、SHA2、SHA3、RIPEMD-160的哈希散列,以及进行AES、DES、Rabbit、RC4、TripleDES加解密。散列算法MD5MD5是一种广泛使......
  • 云技术分享 | 使用快照和 AMI 镜像进行 Amazon EC2 的备份和恢复
    在通过使用 EC2 计算服务的时候,为了更加方便的对虚拟机的环境和数据进行回滚,可以通过亚马逊云科技的快照功能实现。如果您只需要恢复连接到 EC2 实例的单个卷,则可以单独恢复该卷,分离现有卷,然后将恢复的卷连接到您的 EC2 实例。如果您需要恢复整个 EC2 实例,包括其所有关联......
  • 记录一次openpyx使用rich_text报错AttributeError: 'TextBlock' object has no attrib
    先说解决办法:pipinstalllxml报错截图:当时在两个环境中分别使用相同版本openpyxl,相同的代码,一个环境中能成功,另外一个一直报错。排查结果如下:根据报错找到文件:File"\openpyxl\worksheet_writer.py",line147,inwrite_row在155行到158行看到如下代码:ifLXML:......
  • CF1914 D Array Collapse 题解
    LinkCF1914DArrayCollapseQuestion初始给出一个数组\(\{P\}\),数组中每个值都不相同,我们可以选中\(P\)数组中连续的一段,然后删除除了最小值以外的所有元素,求删除多次(包括\(0\)次)后,剩下的数组的数量Solution当时就没怎么往DP方面想,没想到还能这样DP定义\(F[i]\)......