如何在C#winforms应用程序中粘贴剪贴板中的透明图像?

bri*_*ght 8 clipboard image transparent paste winforms

注意:这个问题是关于从剪贴板粘贴,而不是复制到剪贴板.有几篇关于复制到剪贴板的帖子,但找不到解决这个问题的帖子.

如何将具有透明度的图像(例如此图像)粘贴到winforms应用程序中并保持透明度?

我尝试过使用System.Windows.Forms.GetImage(),但会产生一个黑色背景的位图.

我正在从谷歌浏览器复制此图像,谷歌浏览器支持多种剪贴板格式,包括DeviceIndependentBitmapFormat17.

Han*_*ant 13

Chrome以24bpp格式将图像复制到剪贴板.这将透明度变为黑色.您可以从剪贴板中获取32bpp格式,但这需要处理DIB格式.在System.Drawing中没有内置的支持,你需要一个辅助函数来进行转换:

    private Image GetImageFromClipboard() {
        if (Clipboard.GetDataObject() == null) return null;
        if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Dib)) {
            var dib = ((System.IO.MemoryStream)Clipboard.GetData(DataFormats.Dib)).ToArray();
            var width = BitConverter.ToInt32(dib, 4);
            var height = BitConverter.ToInt32(dib, 8);
            var bpp = BitConverter.ToInt16(dib, 14);
            if (bpp == 32) {
                var gch = GCHandle.Alloc(dib, GCHandleType.Pinned);
                Bitmap bmp = null;
                try {
                    var ptr = new IntPtr((long)gch.AddrOfPinnedObject() + 40);
                    bmp = new Bitmap(width, height, width * 4, System.Drawing.Imaging.PixelFormat.Format32bppArgb, ptr);
                    return new Bitmap(bmp);
                }
                finally {
                    gch.Free();
                    if (bmp != null) bmp.Dispose();
                }
            }
        }
        return Clipboard.ContainsImage() ? Clipboard.GetImage() : null;
    }
Run Code Online (Sandbox Code Playgroud)

样品用法:

    protected override void OnPaint(PaintEventArgs e) {
        using (var bmp = GetImageFromClipboard()) {
            if (bmp != null) e.Graphics.DrawImage(bmp, 0, 0);
        }
    }
Run Code Online (Sandbox Code Playgroud)

通过将窗体的BackgroundImage属性设置为stock位图来生成此屏幕截图:

在此输入图像描述

  • 刚注意到 - 图像旋转了180度!上面的图像也从原始图像旋转.知道为什么吗? (2认同)
  • 我能够使用image.RotateFlip(SD.RotateFlipType.Rotate180FlipX)来解决这个问题.不知道为什么上面的代码导致旋转和翻转. (2认同)