How can I get an image out of the clipboard without losing the alpha channel in .NET?

淺唱寂寞╮ 提交于 2019-11-27 04:39:13

问题


I'm trying to save a copied image from the clipboard but it's losing its alpha channel:

Image clipboardImage = Clipboard.GetImage();
string imagePath = Path.GetTempFileName();
clipboardImage.Save(imagePath);

If I copy a 32bit image from PhotoShop or IE/Firefox/Chrome and run the above code, the output loses its alpha channel, instead it is saved against a black background.

The image is saved as PNG, which can contain an alpha channel.

The correct data appears to be in the clipboard because pasting into other applications (such as PhotoShop) retains the alpha channel.

Can anyone put me out of my misery?

Thanks in advance!

Update:

// outputs FALSE
Debug.WriteLine(Image.IsAlphaPixelFormat(Clipboard.GetImage().PixelFormat));

The above suggests that the alpha data is lost as soon as it's taken out of the clipboard. Perhaps I need to get it out of the clipboard some other way?


回答1:


Instead of calling Clipboard.GetImage(), try calling Clipboard.GetDataObject()

This returns an IDataObject, which you can in turn query by calling dataObject.GetFormats(). GetFormats() returns the type formats supported by the Clipboard object - there may be a more precise format supported that you can use to extract the data.




回答2:


It might be like this article suggests, that the Clipboard object, working within Win32, is only able to manage bitmaps, which don't feature the transparent/partially transparent alpha channel. The OLE clipboard is more capable, it seems:

  • Intro
  • Vague support article
  • A bit of discussion about the Win32 clipboard

However, the netez was the best article I found on the topic. (beware I haven't tested this myself)




回答3:


The image is being saved as a bitmap where the transparent pixels are visible on the clipboard so use this code

Bitmap clipboardImage = Clipboard.GetImage();
clipboardImage.MakeTransparent()
string imagePath = Path.GetTempFileName();
clipboardImage.Save(imagePath);



回答4:


I am just using Forms methode. Its not that nice solution like using GetFormat like Kevin is telling us but its more quick and works quiete well at all.

  'Dim bm As BitmapSource = Clipboard.GetImage()'looses alpha channel
                'Dim bmS As New WriteableBitmap(bm)'does work but still without alpha information
                Dim bmF As System.Drawing.Bitmap = System.Windows.Forms.Clipboard.GetImage 'Get working image
                Dim bmS As BitmapSource = TB.Imaging.WPF.BitmapToWpfBitmapSource(bmF, Me) 'convert Bitmap into BitmapSource
                Me.Source = bmS


来源:https://stackoverflow.com/questions/998655/how-can-i-get-an-image-out-of-the-clipboard-without-losing-the-alpha-channel-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!