Reputation: 4699
I am pasting an image (PNG with transparency) from clipboard:
Dim oDataObj As IDataObject = System.Windows.Forms.Clipboard.GetDataObject()
Dim oImgObj As Image = oDataObj.GetData(DataFormats.Bitmap, True)
oImgObj.Save(temp_local, System.Drawing.Imaging.ImageFormat.Png)
or in C#
IDataObject oDataObj = System.Windows.Forms.Clipboard.GetDataObject();
Image oImgObj = oDataObj.GetData(DataFormats.Bitmap, true);
oImgObj.Save(temp_local, System.Drawing.Imaging.ImageFormat.Png);
The problem is the transparency of image is being lost.
Is there any way to keep image transparency?
Upvotes: 1
Views: 1349
Reputation: 4699
I found a brilliant solution from here. I have converted the code to VB.NET to adequate to my question. The following code does the trick:
Private Function GetImageFromClipboard() As Image
If Clipboard.GetDataObject() Is Nothing Then
Return Nothing
End If
If Clipboard.GetDataObject().GetDataPresent(DataFormats.Dib) Then
Dim dib = DirectCast(Clipboard.GetData(DataFormats.Dib), System.IO.MemoryStream).ToArray()
Dim width = BitConverter.ToInt32(dib, 4)
Dim height = BitConverter.ToInt32(dib, 8)
Dim bpp = BitConverter.ToInt16(dib, 14)
If bpp = 32 Then
Dim gch = GCHandle.Alloc(dib, GCHandleType.Pinned)
Dim bmp As Bitmap = Nothing
Try
Dim ptr = New IntPtr(CLng(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 IsNot Nothing Then
bmp.Dispose()
End If
End Try
End If
End If
Return If(Clipboard.ContainsImage(), Clipboard.GetImage(), Nothing)
End Function
Upvotes: 1
Reputation: 3415
That is unfortunately how the clip board works, it copies without transparency.
Upvotes: 1
Reputation: 133
Bitmap objects cannot maintain transparency which is why you are losing the transparency
Upvotes: 1