在C++中,可以有以下两种办法
使用COM接口IThumbnailCache
文档链接:https://learn.microsoft.com/en-us/windows/win32/api/thumbcache/nn-thumbcache-ithumbnailcache
示例代码如下:
1 VOID GetFileThumbnail(PCWSTR path) 2 { 3 HRESULT hr = CoInitialize(nullptr); 4 5 IShellItem* item = nullptr; 6 hr = SHCreateItemFromParsingName(path, nullptr, IID_PPV_ARGS(&item)); 7 8 IThumbnailCache* cache = nullptr; 9 hr = CoCreateInstance( 10 CLSID_LocalThumbnailCache, 11 nullptr, 12 CLSCTX_INPROC, 13 IID_PPV_ARGS(&cache)); 14 15 WTS_CACHEFLAGS flags = WTS_LOWQUALITY; 16 ISharedBitmap* shared_bitmap; 17 hr = cache->GetThumbnail( 18 item, 19 12*16, 20 WTS_EXTRACT, 21 &shared_bitmap, 22 nullptr, 23 nullptr); 24 25 HBITMAP hbitmap = NULL; 26 hr = shared_bitmap->GetSharedBitmap(&hbitmap); 27 shared_bitmap->Release(); 28 cache->Release(); 29 CoUninitialize(); 30 31 //使用hbitmap,使用完成后调用DeleteObject 32 DeleteObject(hbitmap); 33 34 }
前面我一直使用的这种方式,但是最近系统升级后,会报 Generic Error in GDI+
后面我升级成了下面这种方式
使用IShellItemImageFactory接口
1 HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); 2 HBITMAP hbmp = NULL; 3 4 if (SUCCEEDED(hr)) 5 { 6 IShellItemImageFactory* pImageFactory; 7 hr = SHCreateItemFromParsingName(path, NULL, IID_PPV_ARGS(&pImageFactory)); 8 if (SUCCEEDED(hr)) 9 { 10 SIZE size = { 256, 256 }; //图像大小 11 hr = pImageFactory->GetImage(size, SIIGBF_THUMBNAILONLY, &hbmp); 12 pImageFactory->Release(); 13 } 14 CoUninitialize(); 15 16 //使用hbmp,使用完成后调用DeleteObject 17 DeleteObject(hbmp); 18 }
在C#中使用,可以直接nuget引用 WindowsAPICodePack-Shell 包
1 PM> NuGet\Install-Package WindowsAPICodePack-Shell -Version 1.1.1
然后用下面的代码就可以获取文件缩略图
1 ShellFile shellFile = ShellFile.FromFilePath(filepath); 2 Bitmap shellThumb = shellFile.Thumbnail.ExtraLargeBitmap;
标签:文件,缩略图,hr,cache,nullptr,bitmap,获取,hbitmap,shared From: https://www.cnblogs.com/zhaotianff/p/17928871.html