How to convert icon (Bitmap) to ImageSource?

后端 未结 2 1911
猫巷女王i
猫巷女王i 2020-12-20 19:52

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:



        
相关标签:
2条回答
  • 2020-12-20 20:33

    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.

    0 讨论(0)
  • 2020-12-20 20:36

    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());
    
    0 讨论(0)
提交回复
热议问题