如何在C#winforms应用程序中从剪贴板粘贴透明图像? [英] How to paste a transparent image from the clipboard in a C# winforms app?

查看:154
本文介绍了如何在C#winforms应用程序中从剪贴板粘贴透明图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:此问题是关于从剪贴板粘贴而不是复制到剪贴板的问题。有几篇有关复制到剪贴板的文章,但找不到解决此问题的文章。

Note: This question is about pasting from the clipboard, not copying to the clipboard. There are several posts about copying to the clipboard, but couldn't find one that addresses this question.

如何粘贴具有透明度的图像, 插入Winforms应用程序并保持透明度?

How can I paste an image with transparency, for example this one, into a winforms app and retain transparency?

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

I have tried using System.Windows.Forms.GetImage(), but that produces a bitmap with a black background.

我正在从Google Chrome复制该图像,它支持多种剪贴板格式,包括 DeviceIndependentBitmap Format17

I am copying this image from Google Chrome, which supports several clipboard formats, including DeviceIndependentBitmap and Format17.

推荐答案

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

Chrome copies the image to the clipboard in a 24bpp format. Which turns the transparency into black. You can get a 32bpp format out of the clipboard but that requires handling the DIB format. There's no built-in support for that in System.Drawing, you need a little helper function that make the conversion:

    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;
    }

示例用法:

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

使用该表格的BackgroundImage属性生成了此屏幕截图设置为股票位图:

Which produced this screen-shot with the form's BackgroundImage property set to a stock bitmap:

这篇关于如何在C#winforms应用程序中从剪贴板粘贴透明图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆