从剪贴板保存透明图像

时间:2015-11-29 11:08:08

标签: c# image .net-4.0 imaging

我制作了一个监控剪贴板的程序,当复制新图像时,它会保存到文件中。现在,当我从具有透明背景的Paint.net复制图像时,背景充满了白色但是当我从Firefox复制相同的图像时,它保存得很好。这是我正在使用的测试图像:https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png,这是我用来从剪贴板获取图像的代码:

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

使用上面的代码,我保存图像:

Image img = GetImageFromClipboard();
img.RotateFlip(RotateFlipType.Rotate180FlipX);
img.Save("test.png");

我还可以在从Firefox复制图像时看到图片框中的透明度,但是从Paint.net复制时却看不到。

0 个答案:

没有答案
相关问题