Convert HBitmap to Bitmap preserving alpha channel
Asked Answered
T

0

1

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);
    }
Thingumajig answered 14/2, 2012 at 11:3 Comment(1)
You'll need to do a better job describing where this HBITMAP came from. This is otherwise not terribly unsurprising, 24bpp formats are common since GDI doesn't handle alpha and bitmaps are stored upside-down.Raquelraquela

© 2022 - 2024 — McMap. All rights reserved.