I have made a program which monitors the clipboard and when a new image is copied, it gets saved to a file. Now when I copy an image from Paint.net which has transparent background, the background gets filled with white but when I copy the same image from Firefox it saves fine. Here is the test image i'm using: https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png and here is the code which I use to get the image from clipboard:
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;
}
Using the above code, I save the image:
Image img = GetImageFromClipboard();
img.RotateFlip(RotateFlipType.Rotate180FlipX);
img.Save("test.png");
I can also see the transparency in a picturebox when the image is copied from Firefox but not when copied from Paint.net.