Posts Tagged ‘wpf’

Snippet: Icon from shell to ImageSource with alpha channel

Thursday, May 21st, 2009

The following code snippet performs the following task:

  1. Get icon of the given file
  2. Convert in a bitmap preserving the alpha channel
  3. Convert it in a ImageSource

This code is shortcut to retrieve the displayed icon of a file. alternative way to do this is useing shell32.dll and SHGetFileInfo.

I have not used IconBitmapDecoder becuase this class lost the alpha channel.

   1:  public BitmapSource GetIconFromPath(string path)
   2:  {
   3:      System.Drawing.Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(path);
   4:      System.Drawing.Bitmap bitmap = icon.ToBitmap();
   5:      return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(),
   6:              IntPtr.Zero, System.Windows.Int32Rect.Empty,
   7:              System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
   8:  }