-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThumbnailExtractor.cs
More file actions
82 lines (73 loc) · 2.5 KB
/
ThumbnailExtractor.cs
File metadata and controls
82 lines (73 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace SkyCopy
{
public static class ThumbnailExtractor
{
[DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = false)]
private static extern void SHCreateItemFromParsingName(
[MarshalAs(UnmanagedType.LPWStr)] string pszPath,
IntPtr pbc,
ref Guid riid,
[MarshalAs(UnmanagedType.Interface)] out IShellItemImageFactory ppv);
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("bcc18b79-ba16-442f-80c4-8a59c30c463b")]
private interface IShellItemImageFactory
{
void GetImage([In] SIZE size, [In] SIIGBF flags, out IntPtr phbm);
}
[StructLayout(LayoutKind.Sequential)]
private struct SIZE
{
public int cx;
public int cy;
public SIZE(int cx, int cy)
{
this.cx = cx;
this.cy = cy;
}
}
[Flags]
private enum SIIGBF
{
SIIGBF_RESIZETOFIT = 0x00,
SIIGBF_THUMBNAILONLY = 0x02,
}
[DllImport("gdi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool DeleteObject(IntPtr hObject);
/// <summary>
/// Extracts a thumbnail for the given file path using the Windows Shell.
/// Returns null if thumbnail extraction fails.
/// </summary>
public static ImageSource? GetThumbnail(string filePath, int size = 64)
{
IntPtr hBitmap = IntPtr.Zero;
try
{
var iidFactory = new Guid("bcc18b79-ba16-442f-80c4-8a59c30c463b");
SHCreateItemFromParsingName(filePath, IntPtr.Zero, ref iidFactory, out var factory);
factory.GetImage(new SIZE(size, size), SIIGBF.SIIGBF_RESIZETOFIT, out hBitmap);
var source = Imaging.CreateBitmapSourceFromHBitmap(
hBitmap, IntPtr.Zero, Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
source.Freeze();
return source;
}
catch
{
return null;
}
finally
{
if (hBitmap != IntPtr.Zero)
DeleteObject(hBitmap);
}
}
}
}