2012-06-30 18 views
8

注:這個問題是關於從剪貼板粘貼,不能複製到剪貼板。有幾篇關於複製到剪貼板的文章,但找不到解決這個問題的文章。如何在C#winforms應用程序中粘貼剪貼板中的透明圖像?

我如何粘貼圖片的透明度,for example this one,爲WinForms應用程序並保留透明度?

我一直在使用System.Windows.Forms.GetImage()嘗試過,但產生的位圖,背景爲黑色。

我正在從谷歌瀏覽器複製此圖像,它支持多種剪貼板格式,包括DeviceIndependentBitmapFormat17

+0

事實上,它似乎Chrome不居然把有效'Format17'它的剪貼板,也不會MANAG e以編程方式將它放在剪貼板上時粘貼'Format17'。 – Nyerguds

回答

12

Chrome會將圖像中和24bpp格式剪貼板。將透明度變成黑色。您可以從剪貼板中獲取32bpp格式,但需要處理DIB格式。有沒有內置的是,在System.Drawing中的支持,你需要一點輔助函數進行轉換:

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屬性設置爲A股的位圖:

enter image description here

+0

輝煌。非常感謝。 – bright

+2

剛注意到 - 圖像旋轉了180度!上面的圖片也是從原始圖片旋轉而來。任何想法爲什麼? – bright

+2

我能夠解決這個image.RotateFlip(SD.RotateFlipType.Rotate180FlipX)。不過,不知道爲什麼上面的代碼會導致旋轉和翻轉。 – bright

相關問題