3

I am taking an existing PNG image file that has a transparent portion, adding some text on top (using Graphics.DrawString()) before saving the image back to the disk.

I would like to also save the image to the clipboard. However, when I try to paste the resulting image into MS Paint, the transparent regions are light gray. The saved file however retains the transparency correctly.

This is what I currently have:

//reads file into an System.Drawing.Image
FileStream fs = new FileStream(fileLocation, FileMode.Open, FileAccess.Read);   
Image image = Image.FromStream(fs);
fs.Close();

//add text to image via System.Drawing.Graphics
Bitmap myBitmap = new Bitmap(image);
Graphics g = Graphics.FromImage(myBitmap);
g.DrawString(textToAdd, new Font("Tahoma", 14), System.Drawing.Brushes.Black, new PointF(0, 0));

//save modified image back to disk (transparency works)
myBitmap.Save(fileLocation, System.Drawing.Imaging.ImageFormat.Png);

//Copy to clipboard (transparent areas are now gray)
System.Windows.Forms.Clipboard.SetImage(myBitmap);
Typer525
  • 86
  • 1
  • 8
  • This should work. It works here! Bitmap bmp = new Bitmap("D:\\2RButtons.png"); Graphics g = Graphics.FromImage(bmp); g.DrawString("**", new Font("Tahoma", 6), System.Drawing.Brushes.Red, new PointF(0, 0)); pictureBox1.Image = bmp; Clipboard.SetImage(bmp); pictureBox1.Image = Clipboard.GetImage();`` and all is well, tranparency is preserved. – TaW Jun 19 '14 at 23:35
  • ..pasting into Paint also works fine. (On a win 8.1 machine).. – TaW Jun 19 '14 at 23:47

2 Answers2

2

The Windows clipboard, by default, does not support transparency, but you can put content on the clipboard in many types together to make sure most applications find some type in it that they can use. Generally, if, in addition to the normal nontransparent clipboard Bitmap format, you put the image on the clipboard in both PNG and DIB formats, most applications will be able to use at least one of them to get the image in a format they support as being transparent.

I detailed how to do that (both copying to and pasting from) in this answer:

https://stackoverflow.com/a/46424800/395685

Nyerguds
  • 5,360
  • 1
  • 31
  • 63
-1

Answering my own question.

What I have does not work in my current environment (Windows 7) because Win7 does not support transparency in its clipboard. However it does work in a Windows 8 environment.

Typer525
  • 86
  • 1
  • 8
  • Have you tried paint.net? I seem to remember copying transparent images on my win7 machine. It doesn't paste into paint correctly, but I can into paint.net, and photoshop. – Matches Jun 23 '14 at 21:54
  • The Windows clipboard can have multiple objects on it simultaneously. Modern apps cheat by simply using different formats than just the standard clipboard "Bitmap" format. A common one is a `MemoryStream` containing the bytes of a png image, put on the clipboard as data type "PNG". – Nyerguds Sep 26 '17 at 12:34