如何将图标(位图)转换为图像源(ImageSource)?

6

我的WPF应用程序中有一个按钮和名为image1的图像。我想从位置图标或文件路径添加图像1的图像源。这是我的代码:

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”

如何解决这个问题?


这可能会有所帮助:https://dev59.com/UF8d5IYBdhLWcg3w8GC-#26261562 - 15ee8f99-57ff-4f92-890c-b56153
2个回答

8
Farhan Anam提出的解决方案可行,但不是理想的:图标是从文件加载,转换为位图,保存到流中,然后从流重新加载。这相当低效。
另一种方法是使用System.Windows.Interop.Imaging类及其CreateBitmapSourceFromHIcon方法:
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块,在转换后处理原始图标。不这样做会导致句柄泄漏。

是的,我也这么想... +1 :) - Fᴀʀʜᴀɴ Aɴᴀᴍ
1
注意:CreateBitmapSourceFromHIcon必须在GUI线程上调用。否则会抛出异常。 - user299771

6
您得到的错误是因为您试图将位图分配为图像的源。要纠正这个问题,可以使用以下函数:
BitmapImage BitmapToImageSource(Bitmap bitmap)
{
    using (MemoryStream memory = new MemoryStream())
    {
        bitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Bmp);
        memory.Position = 0;
        BitmapImage bitmapimage = new BitmapImage();
        bitmapimage.BeginInit();
        bitmapimage.StreamSource = memory;
        bitmapimage.CacheOption = BitmapCacheOption.OnLoad;
        bitmapimage.EndInit();

        return bitmapimage;
    }
}

就像这样:

image1.Source = BitmapToImageSource(ico.ToBitmap());

感谢Farhab Anam,你的代码给了我解决方案。非常感谢。 :) - Yousuf
你好。我在我的image1控件中有一张黑色背景的图片。我能把背景颜色从黑色改成白色吗?谢谢。 - Yousuf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接