我一直在Google和Stack Overflow中搜索,但找不到有效的示例。
我需要将 HBitmap 转换为托管 .NET 位图,但以下代码不保留 alpha 通道。
private static Bitmap GetBitmapFromHBitmap(IntPtr nativeHBitmap)
{
Bitmap bmp = Bitmap.FromHbitmap(nativeHBitmap);
return bmp;
}
我在 SO 中找到了这个答案,但它对我不起作用,该示例保留了透明度,但是它将我的图像在 Y 轴上翻转了 180º 并将其旋转了 180º。我不知道为什么。
This other example似乎有效,但它是C++
有人在 C# 中工作,而且非常重要,没有内存泄漏?
提前致谢。
编辑:关于@Hans Passant 的评论,我使用以下代码获取 HBitmap(这是从操作系统(仅 Vista 和 Win7)获取缩略图或图标的 shell 调用。
private static IntPtr GetHBitmap(string fileName, int width, int height, ThumbnailOptions options)
{
IShellItem nativeShellItem;
Guid shellItem2Guid = new Guid(IShellItem2Guid);
int retCode = SHCreateItemFromParsingName(fileName, IntPtr.Zero, ref shellItem2Guid, out nativeShellItem);
NativeSize nativeSize = new NativeSize();
nativeSize.Width = width;
nativeSize.Height = height;
IntPtr hBitmap;
HResult hr = ((IShellItemImageFactory)nativeShellItem).GetImage(nativeSize, options, out hBitmap);
Marshal.ReleaseComObject(nativeShellItem);
if (hr == HResult.Ok) return hBitmap;
throw Marshal.GetExceptionForHR((int) hr);
}