C# Convert BitmapFrame to Icon and Vice Versa

本文介绍如何在从WinForms迁移到WPF的过程中转换图标和图像资源。具体包括使用BitmapFrame转换为Icon的方法及反之亦然的过程。需要注意的是直接转换可能导致GDI句柄泄露。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

In the transition from Winform era to the Wpf era. Different type of image classes are used for icons, buttons images and etc....

 

The pre-world uses the Icon class (System.Drawing), while the newer wpf will uses ImageSource, more specifically, ImageSource's concrete derived classes such as BigmapFrame or BitmapImage (System.Windows.Media.Imaging);

 

 

Below shows the code that helps you to convert from BitmapFrame to Icon

 

 

 

private static Icon ConvertFromBitmapFrame(BitmapFrame bitmapFrame)
    {
      Debug.Assert(bitmapFrame != null);

      var ms = new MemoryStream();
      var encoder = new PngBitmapEncoder();
      encoder.Frames.Add(bitmapFrame);
      encoder.Save(ms);
      ms.Seek(0, SeekOrigin.Begin);
      var bmp = new Bitmap(ms);
      return Icon.FromHandle(bmp.GetHicon());
    }

 

 

the above code may have handle leakage as the bmp.GetHIcon will leak the the GDI handle to the wild.

 

and below shows code to convert from Icon to ImageSource. 

 

 

 

    private BitmapFrame ConvertFromIcon(Icon icon)
    {
      var memoryStream = new MemoryStream();
      icon.Save(memoryStream);
      memoryStream.Seek(0, SeekOrigin.Begin);
      return BitmapFrame.Create(memoryStream);
    }
 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值