如何将图标(位图)转换为ImageSource? [英] How to convert icon (Bitmap) to ImageSource?
问题描述
我的wpf应用程序中有一个按钮和一个名为image1的图像.我想从位置或文件路径的文件图标添加image1的图像源.这是我的代码:
I have a button and an image named as image1 in my wpf app. I want add image source of the image1 from a file icon of a location or file path. Here is my code:
using System.Windows;
using System.Windows.Media.Imaging;
using System.IO;
using System.Drawing;
namespace WpfApplication2
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Icon ico = System.Drawing.Icon.ExtractAssociatedIcon(@"C:\WINDOWS\system32\notepad.exe");
image1.Source = ico.ToBitmap();
}
}
}
错误提示
无法将类型'System.Drawing.Bitmap'隐式转换为'System.Windows.Media.ImageSource'
Cannot implicitly convert type 'System.Drawing.Bitmap' to 'System.Windows.Media.ImageSource'
如何解决这个问题?
推荐答案
Farhan Anam建议的解决方案可以使用,但并不理想:从文件中加载图标,将其转换为位图,保存到流中并重新加载从流中.效率很低.
The solution suggested by Farhan Anam will work, but it's not ideal: the icon is loaded from a file, converted to a bitmap, saved to a stream and reloaded from the stream. That's quite inefficient.
另一种方法是使用 System.Windows.Interop.Imaging
类及其
Another approach is to use the System.Windows.Interop.Imaging
class and its CreateBitmapSourceFromHIcon
method:
private ImageSource IconToImageSource(System.Drawing.Icon icon)
{
return Imaging.CreateBitmapSourceFromHIcon(
icon.Handle,
new Int32Rect(0, 0, icon.Width, icon.Height),
BitmapSizeOptions.FromEmptyOptions());
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
using (var ico = System.Drawing.Icon.ExtractAssociatedIcon(@"C:\WINDOWS\system32\notepad.exe"))
{
image1.Source = IconToImageSource(ico);
}
}
请注意在转换后将 using
块用于处置原始图标.不这样做会导致手柄泄漏.
Note the using
block to dispose the original icon after you converted it. Not doing this will cause handle leaks.
这篇关于如何将图标(位图)转换为ImageSource?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!