我想得到一个文件夹的缩略图图像,但我没有找到任何方法来做与WPF。对于UWP,有一个函数StorageFolder.GetThumbnailAsync()
。但在WPF,我没有找到任何解决方案。
发布于 2020-07-08 04:19:44
使用http://stackoverflow.com/a/2994451/1360389上提到的Windows API Code Pack可能会有帮助。对文件使用ShellFile.FromFilePath(FilePath).Thumbnail.BitmapSource
,对文件夹使用ShellFolder.FromParsingName(FolderPath).Thumbnail.BitmapSource
。
发布于 2020-07-07 04:47:07
我可以通过pinvoke以一种不是很干净的方式来做这件事,但它工作起来就像它应该看到的代码一样(使用GetIcon
方法):
public static class UITools
{
private const uint FILE_ATTRIBUTE_NORMAL = 0x00000080;
private const uint FILE_ATTRIBUTE_DIRECTORY = 0x00000010;
/// <summary>
/// Converts a <see cref="System.Drawing.Bitmap"/> into a WPF <see cref="BitmapSource"/>.
/// </summary>
/// <remarks>Uses GDI to do the conversion. Hence the call to the marshalled DeleteObject.
/// </remarks>
/// <param name="source">The source bitmap.</param>
/// <returns>A BitmapSource</returns>
public static BitmapSource ToBitmapSource(this System.Drawing.Bitmap source)
{
BitmapSource bitSrc = null;
var hBitmap = source.GetHbitmap();
try
{
bitSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
hBitmap,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
}
catch (Win32Exception)
{
bitSrc = null;
}
finally
{
DeleteObject(hBitmap);
}
return bitSrc;
}
public static BitmapSource GetIcon(string path,bool isDirectory)
{
IntPtr hIcon = GetJumboIcon(GetIconIndex(path,isDirectory));
BitmapSource icon = null;
using (Icon ico = (Icon)System.Drawing.Icon.FromHandle(hIcon).Clone())
{
icon = ico.ToBitmap().ToBitmapSource();
}
DestroyIcon(hIcon);
return icon;
}
internal static int GetIconIndex(string pszFile,bool isDirectory)
{
uint attributes = FILE_ATTRIBUTE_NORMAL;
if (isDirectory)
attributes |= FILE_ATTRIBUTE_DIRECTORY;
SHFILEINFO sfi = new SHFILEINFO();
NativeMethods.SHGetFileInfo(pszFile
, attributes //0
, ref sfi
, (uint)System.Runtime.InteropServices.Marshal.SizeOf(sfi)
, (uint)(SHGFI.SysIconIndex | SHGFI.LargeIcon | SHGFI.UseFileAttributes));
return sfi.iIcon;
}
// 256*256
internal static IntPtr GetJumboIcon(int iImage)
{
IImageList spiml = null;
Guid guil = new Guid(IID_IImageList); //or IID_IImageList2
SHGetImageList(SHIL_EXTRALARGE, ref guil, ref spiml);
IntPtr hIcon = IntPtr.Zero;
spiml.GetIcon(iImage, ILD_TRANSPARENT | ILD_IMAGE, ref hIcon); //
return hIcon;
}
}
正如您所看到的,这适用于文件和文件夹。您可以使用我在不久前开发的一个小工具来查看它的运行情况:GitHub
https://stackoverflow.com/questions/62763998
复制相似问题