I have been trying to tackle the age-old issue of .NET (all versions) not supporting TRUE transparency natively, and after reading thousands of articles, questions/answers, forums, msdn articles, etc, have come up empty handed aside from being able to do this by using an entire form, of which, no controls are visible (see http://www.codeproject.com/Articles/1822/Per-Pixel-Alpha-Blend-in-C )
I have partially given up this search and instead, have decided to be satisfied by using an MDIParent/Client situation where each graphic/text is drawn directly onto the form.
The problem that I have with this, is that when I save out, with transparency, I end up with a blob around any shadows which I believe (but am unsure) is the PNG is being saved at a lower resolution or loss of alpha channels or something, that MakeTransparent(Insert Color Here), just isn't being satisfied with. If you can show where this process is going so terribly wrong ... please show me.
Input image
Output Image
The code I am using is as follows:
Imports Graphics
Public Class PictureForm
Private Declare Auto Function BitBlt Lib "gdi32.dll" (ByVal _
hdcDest As IntPtr, ByVal nXDest As Integer, ByVal _
nYDest As Integer, ByVal nWidth As Integer, ByVal _
nHeight As Integer, ByVal hdcSrc As IntPtr, ByVal nXSrc _
As Integer, ByVal nYSrc As Integer, ByVal dwRop As _
System.Int32) As Boolean
Private Const SRCCOPY As Integer = &HCC0020
Public Graphic As Drawing.Graphics
Private Sub PictureForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Show()
Graphic = Me.CreateGraphics
Graphic.CompositingQuality = Drawing2D.CompositingQuality.HighQuality
Graphic.DrawImage(Image.FromFile("C:\Users\Daniel\Downloads\PNG-icon.png"), 35, 22)
Dim bmp As Bitmap = GetFormImage()
bmp.MakeTransparent(Color.White)
bmp.Save("test.png", System.Drawing.Imaging.ImageFormat.Png)
bmp.Dispose()
End Sub
Public Function GetFormImage() As Bitmap
' Get this form's Graphics object.
Dim me_gr As Drawing.Graphics = Me.CreateGraphics
' Make a Bitmap to hold the image.
Dim bm As New Bitmap(Me.ClientSize.Width, Me.ClientSize.Height, me_gr)
Dim bm_gr As Drawing.Graphics = Drawing.Graphics.FromImage(bm)
Dim bm_hdc As IntPtr = bm_gr.GetHdc
' Get the form's hDC. We must do this after
' creating the new Bitmap, which uses me_gr.
Dim me_hdc As IntPtr = me_gr.GetHdc
' BitBlt the form's image onto the Bitmap.
BitBlt(bm_hdc, 0, 0, Me.ClientSize.Width, _
Me.ClientSize.Height, _
me_hdc, 0, 0, SRCCOPY)
me_gr.ReleaseHdc(me_hdc)
bm_gr.ReleaseHdc(bm_hdc)
' Return the result.
Return bm
End Function
End Class
Additionaly, you will notice that the letters in the first image have no been rendered transparent in the output.