Convert HBitmap to Bitmap preserving alpha channel

2019-06-05 18:46发布

I have been searching in Google and Stack Overflow, and I cannot find a working example.

I need to convert a HBitmap to a Managed .NET bitmap, but the following code does not preserve the alpha channel.

    private static Bitmap GetBitmapFromHBitmap(IntPtr nativeHBitmap)
    {
        Bitmap bmp = Bitmap.FromHbitmap(nativeHBitmap);
        return bmp;
    }

I found this answer in SO, but it does not work for me, the example preserves the transparency, however it flips my image 180º in Y axis and also rotate it 180º. I don't know why.

This other example seems to work, but it is C++

Someone has this working in C#, and very important, without memory leaks?

Thanks in advance.


EDIT: Regarding the comment from @Hans Passant, I use the following code to get the HBitmap (it's a shell call to get the thumbnail or icon from the OS (only Vista and Win7).

    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);
    }

1条回答
虎瘦雄心在
2楼-- · 2019-06-05 19:16

Please take a look at Preserving the alpha channel when converting images. It seems that it is your case.

查看更多
登录 后发表回答