Save Bitmap to ICO file, with transparency

2019-09-12 12:38发布

I'm trying to save a bitmap to a ico file format, but the result file is a PNG image with the extension changed to "ico".

Why the ImageFormat Class is saving my Bitmap as PNG format if I choosed Icon format? and then how to save the ico file?

PS: I need to save the ICO with transparency

This is how I call the proc:

Save_Icon(Resize_Image(Bitmap.FromFile(PictureBox_Regedit.Tag), 24, 24), "Regedit.ico")

And this is the res of the code

Private Sub Save_Icon(ByVal Source As Bitmap, ByVal Filename As String)

    Try
        If Not Directory.Exists(AppDir) Then Directory.CreateDirectory(AppDir)
        If Not Directory.Exists(AppIcons) Then Directory.CreateDirectory(AppIcons)
        Source.MakeTransparent()
        Source.Save(Path.Combine(AppIcons, Filename), ImageFormat.Icon)
    Catch ex As Exception
        Throw New Exception(ex.Message)
    End Try

End Sub

Private Function Resize_Image(ByVal img As Image, ByVal Width As Int32, ByVal Height As Int32) As Bitmap
    Dim Bitmap_Source As New Bitmap(img)
    Dim Bitmap_Dest As New Bitmap(CInt(Width), CInt(Height))
    Dim Graphic As Graphics = Graphics.FromImage(Bitmap_Dest)
    Graphic.DrawImage(Bitmap_Source, 0, 0, Bitmap_Dest.Width + 1, Bitmap_Dest.Height + 1)
    Return Bitmap_Dest
End Function

2条回答
贪生不怕死
2楼-- · 2019-09-12 13:10

As it says in the documentation:

When you call MakeTransparent, the bitmap will be converted to the Format32bppArgb format, as this format supports an alpha channel.

Icons do not support alpha channels. Icon transparency is achieved in a different way. The Save method does its best to keep the structure you're creating intact, hence the PNG result.

查看更多
地球回转人心会变
3楼-- · 2019-09-12 13:27

"Save As" in editing applications always implies conversion, which you are not doing here.

You can for example use the Bitmap.GetHicon Method to convert your source to an icon format, and use the System.Drawing Icon Class from there. Don't forget to destroy the Hicon after that.

Problem is, if I remember correctly, that's where the .NET Framework leaves you. I cannot recall transparency functionality, and I've switched to the FreeImage library a couple of years ago, and do everything with that since.

查看更多
登录 后发表回答