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?
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With