简体   繁体   English

将HBitmap转换为保留Alpha通道的位图

[英]Convert HBitmap to Bitmap preserving alpha channel

I have been searching in Google and Stack Overflow , and I cannot find a working example. 我一直在GoogleStack Overflow中进行搜索,但找不到有效的示例。

I need to convert a HBitmap to a Managed .NET bitmap, but the following code does not preserve the alpha channel . 我需要将HBitmap转换为Managed .NET位图,但是以下代码不保留alpha通道

    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º. 在SO中找到了这个答案 ,但是它对我不起作用,该示例保留了透明度,但是它将图像在Y轴上翻转了180º,并将其旋转了180º。 I don't know why. 我不知道为什么

This other example seems to work, but it is C++ 这个其他示例似乎可行,但是它是C ++

Someone has this working in C#, and very important, without memory leaks? 有人使用C#进行这项工作,并且非常重要,没有内存泄漏吗?

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). 编辑 :关于@Hans Passant的评论,我使用以下代码获取HBitmap(这是从OS(仅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);
    }

Please take a look at Preserving the alpha channel when converting images . 转换图像时,请查看保留alpha通道 It seems that it is your case. 看来这是您的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM