How to convert icon (bitmap) to ImageSource?

I have a button and an image named image1 in my wpf application. I want to add the image1 image source from the file icon of the 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();
        }
    }
}

And the error says

Cannot implicitly convert type 'System.Drawing.Bitmap' to 'System.Windows.Media.ImageSource'

How to solve this problem?

+4
source share
2 answers

The solution proposed by Farhan Anam will work, but it is not perfect: the icon is loaded from the file, converted to a bitmap, saved in the stream, and reloaded from the stream. This is pretty inefficient.

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, . .

+5

, , , . , :

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());
+4

Source: https://habr.com/ru/post/1620797/


All Articles