从BitmapSource中删除alpha

时间:2009-11-15 16:44:57

标签: c# wpf gdi bitmapsource

我使用BitBlt()和CreateBitmapSourceFromHBitmap()将窗口捕获为BitmapSource,我可以在WPF应用程序的Image元素上显示。但由于某些原因,它捕获的大多数应用程序都是透明的。以下是正在发生的事情的来源与捕获图像:

https://userpages.umbc.edu/~smyth1/images/screencap.PNG
(来源:umbc.edu

它是灰色的,因为它所在窗口的背景是灰色的。无论我给窗户的背景是什么。

如何让拍摄的图像更准确地反映原始图像?

1 个答案:

答案 0 :(得分:4)

您的代码中的问题可能是由于您使用的Win32 API(CreateCompatibleDCSelectObjectCreateBitmap ...)。我尝试使用更简单的代码,只使用GetDCBitBlt,它对我来说很好用。这是我的代码:

    public static Bitmap Capture(IntPtr hwnd)
    {
        IntPtr hDC = GetDC(hwnd);
        if (hDC != IntPtr.Zero)
        {
            Rectangle rect = GetWindowRectangle(hwnd);
            Bitmap bmp = new Bitmap(rect.Width, rect.Height);
            using (Graphics destGraphics = Graphics.FromImage(bmp))
            {
                BitBlt(
                    destGraphics.GetHdc(),
                    0,
                    0,
                    rect.Width,
                    rect.Height,
                    hDC,
                    0,
                    0,
                    TernaryRasterOperations.SRCCOPY);
            }
            return bmp;
        }
        return null;
    }

我在Windows窗体和WPF(使用Imaging.CreateBitmapSourceFromHBitmap)中尝试过,它在两种情况下都适用于相同的屏幕截图(Firefox中的SO页面)。

HTH,

相关问题