Accessing thumbnails that don't exist
See the question and my original answer on StackOverflowHere is a piece of code that extracts thumbnail bitmaps (using Windows Vista or higher only). It's based on the cool IShellItemImageFactory interface:
static void Main(string[] args)
{
// you can use any type of file supported by your windows installation.
string path = @"c:\temp\whatever.pdf";
using (Bitmap bmp = ExtractThumbnail(path, new Size(1024, 1024), SIIGBF.SIIGBF_RESIZETOFIT))
{
bmp.Save("whatever.png", ImageFormat.Png);
}
}
public static Bitmap ExtractThumbnail(string filePath, Size size, SIIGBF flags)
{
if (filePath == null)
throw new ArgumentNullException("filePath");
// TODO: you might want to cache the factory for different types of files
// as this simple call may trigger some heavy-load underground operations
IShellItemImageFactory factory;
int hr = SHCreateItemFromParsingName(filePath, IntPtr.Zero, typeof(IShellItemImageFactory).GUID, out factory);
if (hr != 0)
throw new Win32Exception(hr);
IntPtr bmp;
hr = factory.GetImage(size, flags, out bmp);
if (hr != 0)
throw new Win32Exception(hr);
return Bitmap.FromHbitmap(bmp);
}
[Flags]
public enum SIIGBF
{
SIIGBF_RESIZETOFIT = 0x00000000,
SIIGBF_BIGGERSIZEOK = 0x00000001,
SIIGBF_MEMORYONLY = 0x00000002,
SIIGBF_ICONONLY = 0x00000004,
SIIGBF_THUMBNAILONLY = 0x00000008,
SIIGBF_INCACHEONLY = 0x00000010,
SIIGBF_CROPTOSQUARE = 0x00000020,
SIIGBF_WIDETHUMBNAILS = 0x00000040,
SIIGBF_ICONBACKGROUND = 0x00000080,
SIIGBF_SCALEUP = 0x00000100,
}
[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
private static extern int SHCreateItemFromParsingName(string path, IntPtr pbc, [MarshalAs(UnmanagedType.LPStruct)] Guid riid, out IShellItemImageFactory factory);
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("bcc18b79-ba16-442f-80c4-8a59c30c463b")]
private interface IShellItemImageFactory
{
[PreserveSig]
int GetImage(Size size, SIIGBF flags, out IntPtr phbm);
}
Additional notes:
- The
GetImage
method has various interesting flags (SIIGBF
) you can play with. - For performance reasons, you can cache the factories. For example, .PDF files requires the whole Adobe Reader .exe to load in the background.
- When talking to the shell (Windows Explorer), you want to make sure your process runs at the same UAC level than the shell otherwise, for security reasons, some operations will fail. So for example, if you run your process from F5 or CTRL+F5 in Visual Studio, and your Visual Studio runs as admin, your process may not be able to retrieve thumbnails, while it will work when run double-clicking on the .exe from the explorer. The
REGDB_E_CLASSNOTREG
is a typical kind of error you may get in these cases.