public static Bitmap ExtractImage(FileInfoEx entry, Size size, bool quality) { try { IntPtr iExtractImagePtr = IntPtr.Zero; IExtractImage iExtractImage = null; if (GetIExtractImage(entry, out iExtractImagePtr, out iExtractImage)) try { ShellDll.ShellAPI.SIZE prgSize = new ShellAPI.SIZE() { cx = size.Width, cy = size.Height }; IExtractImageFlags flags = IExtractImageFlags.Cache | IExtractImageFlags.Aspect; if (quality) flags |= IExtractImageFlags.Quality; StringBuilder location = new StringBuilder(260, 260); try { int pdwPriority = 1; iExtractImage.GetLocation(location, location.Capacity, ref pdwPriority, ref prgSize, 32, ref flags); } catch (COMException) { } IntPtr ptrBitmapImage = IntPtr.Zero; iExtractImage.Extract(out ptrBitmapImage); if (ptrBitmapImage != IntPtr.Zero) return Bitmap.FromHbitmap(ptrBitmapImage); } catch (Exception) { } finally { if (iExtractImage != null) Marshal.ReleaseComObject(iExtractImage); if (iExtractImagePtr != IntPtr.Zero) Marshal.Release(iExtractImagePtr); } return null; } catch (NotSupportedException) { return null; } }
private bool GetThumbnail(string file, IntPtr pidl, IShellFolder item) { IntPtr bmp = IntPtr.Zero; IExtractImage extractImage = null; try { string pidlPath = PathFromPidl(pidl); if (Path.GetFileName(pidlPath).ToUpper().Equals(Path.GetFileName(file).ToUpper())) { // we have the item: IUnknown iunk = null; int prgf; Guid iidExtractImage = new Guid("BB2E617C-0920-11d1-9A0B-00C04FC2D6C1"); item.GetUIObjectOf(IntPtr.Zero, 1, ref pidl, ref iidExtractImage, out prgf, ref iunk); extractImage = (IExtractImage)iunk; if (extractImage != null) { //Got an IExtractImage object! ShellAPI.SIZE size = new ShellAPI.SIZE { cx = this.DesiredSize.Width, cy = this.DesiredSize.Height }; StringBuilder location = new StringBuilder(260, 260); int priority = 0; const int requestedColourDepth = 32; const IEIFLAG flags = IEIFLAG.IEIFLAG_ASPECT | IEIFLAG.IEIFLAG_SCREEN; int uFlags = (int)flags; extractImage.GetLocation(location, location.Capacity, ref priority, ref size, requestedColourDepth, ref uFlags); extractImage.Extract(out bmp); if (bmp != IntPtr.Zero) { // create the image object: this.ThumbNail = Image.FromHbitmap(bmp); // is thumbNail owned by the Bitmap? } Marshal.ReleaseComObject(extractImage); extractImage = null; } return true; } else { return false; } } catch (Exception) { if (bmp != IntPtr.Zero) { UnManagedMethods.DeleteObject(bmp); } if (extractImage != null) { Marshal.ReleaseComObject(extractImage); } throw; } }