How to paste transparent image from clipboard into winforms c # application?

Note. This question is about pasting from the clipboard, not copying to the clipboard. There are several messages about copying to the clipboard, but could not find the answer to this question.

How can I insert an image with transparency, for example, this , into a winforms application and maintain transparency?

I tried using System.Windows.Forms.GetImage() , but this creates a bitmap with a black background.

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

+8
clipboard image paste winforms transparent
source share
1 answer

Chrome copies the image to the clipboard in 24bpp format. Which turns transparency into black. You can get the 32bpp format from the clipboard, but this requires processing of the DIB format. There is no built-in support for System.Drawing, you need a little helper function that does 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; } 

Sample Usage:

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

Created this screenshot using the BackgroundImage property set in the bitmap:

enter image description here

+12
source share

All Articles