Skip to main content
 首页 » 编程设计

c#之从 BitmapSource 中移除 alpha

2024年02月24日35lexus

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


(来源:umbc.edu)

它是灰色的,因为它所在的窗口的背景是灰色的。无论我为窗口提供什么背景,它都会显示出来。

如何让截取的图像更准确地反射(reflect)原图?

请您参考如下方法:

您的代码中的问题可能是由于您使用的 Win32 API(CreateCompatibleDC、SelectObject、CreateBitmap...) .我尝试使用更简单的代码,仅使用 GetDC 和 BitBlt,它对我来说工作正常。这是我的代码:

    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),对于相同的屏幕截图(SO 页面在 Firefox 中),它在两种情况下都工作正常。

HTH,