Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert transparent PNG to System.Drawing.Icon in code

Tags:

c#

.net

icons

wpf

png

I'm looking to convert a transparent PNG image as an ImageSource into a System.Drawing.Icon that respects the transparency of the PNG.

WPF can somehow do this internally if you set the icon for a window to a PNG ImageSource, but is there any way I can do this manually? Specifically I need this to set the system tray notify icon and I really want to avoid using clumsy .ico format resources.

like image 306
devios1 Avatar asked Feb 04 '11 15:02

devios1


2 Answers

You can write

Icon.FromHandle(image.GetHIcon())

You'll need to explicitly destroy the icon when you're done with it:

[DllImport("user32.dll", CharSet = CharSet.Auto)]
extern static bool DestroyIcon(IntPtr handle);

DestroyIcon(newIcon.Handle);
like image 84
SLaks Avatar answered Oct 16 '22 04:10

SLaks


I'm looking for this~ Here is one, but not very good!

        Icon icon;
        Image source = Image.FromFile(picturefile, true);

        Bitmap target = new Bitmap(iconsize, iconsize,
            System.Drawing.Imaging.PixelFormat.Format32bppArgb);

        Graphics g = Graphics.FromImage(target);
        g.DrawImage(source, 0, 0, iconsize, iconsize);

        //target.Save("c:\\temp\\forest.bmp");

        icon = Icon.FromHandle(target.GetHicon());

        FileStream fs = File.Create(iconfile);
        icon.Save(fs);
        fs.Close();

        icon.Dispose();
        target.Dispose();
        source.Dispose();
like image 45
Saiya Avatar answered Oct 16 '22 04:10

Saiya