Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert icon (Bitmap) to ImageSource?

Tags:

c#

wpf

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

And the error is saying

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

How to solve this problem?

like image 556
Yousuf Avatar asked Dec 18 '15 17:12

Yousuf


2 Answers

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.

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

Note the using block to dispose the original icon after you converted it. Not doing this will cause handle leaks.

like image 63
Thomas Levesque Avatar answered Nov 12 '22 06:11

Thomas Levesque


The error you get is because you try to assign a bitmap as the source of an image. To rectify that, use this function:

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

like this:

image1.Source = BitmapToImageSource(ico.ToBitmap());
like image 6
Fᴀʀʜᴀɴ Aɴᴀᴍ Avatar answered Nov 12 '22 07:11

Fᴀʀʜᴀɴ Aɴᴀᴍ