6

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?

Ondrej Janacek
  • 12,486
  • 14
  • 59
  • 93
Yousuf
  • 313
  • 4
  • 12

2 Answers2

8

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.

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
6

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());
Fᴀʀʜᴀɴ Aɴᴀᴍ
  • 6,131
  • 5
  • 31
  • 52
  • Thanks Farhab Anam. Your code has given me the solution. Thanks a lot. :) – Yousuf Dec 18 '15 at 18:07
  • hello again. I am having a image with a black background in my image1 control. Can i change the background color from black to white? thanks. – Yousuf Dec 18 '15 at 18:11