在C++中,可以有以下两种办法
使用COM接口IThumbnailCache
文档链接:IThumbnailCache (thumbcache.h) - Win32 apps | Microsoft Learn
示例代码如下:
VOID GetFileThumbnail(PCWSTR path)
{
HRESULT hr = CoInitialize(nullptr);
IShellItem* item = nullptr;
hr = SHCreateItemFromParsingName(path, nullptr, IID_PPV_ARGS(&item));
IThumbnailCache* cache = nullptr;
hr = CoCreateInstance(
CLSID_LocalThumbnailCache,
nullptr,
CLSCTX_INPROC,
IID_PPV_ARGS(&cache));
WTS_CACHEFLAGS flags = WTS_LOWQUALITY;
ISharedBitmap* shared_bitmap;
hr = cache->GetThumbnail(
item,
12*16,
WTS_EXTRACT,
&shared_bitmap,
nullptr,
nullptr);
HBITMAP hbitmap = NULL;
hr = shared_bitmap->GetSharedBitmap(&hbitmap);
shared_bitmap->Release();
cache->Release();
CoUninitialize();
//使用hbitmap,使用完成后调用DeleteObject
DeleteObject(hbitmap);
}
前面我一直使用的这种方式,但是最近系统升级后,会报 Generic Error in GDI+
后面我升级成了下面这种方式
使用IShellItemImageFactory接口
文档链接:IShellItemImageFactory (shobjidl_core.h) - Win32 apps | Microsoft Learn
HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
HBITMAP hbmp = NULL;
if (SUCCEEDED(hr))
{
IShellItemImageFactory* pImageFactory;
hr = SHCreateItemFromParsingName(path, NULL, IID_PPV_ARGS(&pImageFactory));
if (SUCCEEDED(hr))
{
SIZE size = { 256, 256 }; //图像大小
hr = pImageFactory->GetImage(size, SIIGBF_THUMBNAILONLY, &hbmp);
pImageFactory->Release();
}
CoUninitialize();
//使用hbmp,使用完成后调用DeleteObject
DeleteObject(hbmp);
}
在C#中使用,可以直接nuget引用 WindowsAPICodePack-Shell 包
PM> NuGet\Install-Package WindowsAPICodePack-Shell -Version 1.1.1
然后用下面的代码就可以获取文件缩略图
ShellFile shellFile = ShellFile.FromFilePath(filepath); Bitmap shellThumb = shellFile.Thumbnail.ExtraLargeBitmap;标签:缩略图,C#,cache,nullptr,C++,bitmap,hr,hbitmap,shared From: https://blog.csdn.net/zhaotianff/article/details/140769502