【问题标题】:Convert transparent PNG to System.Drawing.Icon in code在代码中将透明 PNG 转换为 System.Drawing.Icon
【发布时间】:2011-06-21 10:55:14
【问题描述】:

我希望将透明的 PNG 图像作为 ImageSource 转换为尊重 PNG 透明度的 System.Drawing.Icon。

如果您将窗口的图标设置为 PNG ImageSource,WPF 可以在内部以某种方式执行此操作,但是有什么方法可以手动执行此操作吗?具体来说,我需要这个来设置系统托盘通知图标,我真的想避免使用笨拙的 .ico 格式资源。

【问题讨论】:

  • 附带说明,windows vista+ 支持实际为 PNG 格式的 .ico 文件。这对你有用吗? blogs.msdn.com/b/oldnewthing/archive/2010/10/22/10079192.aspx
  • 除非 .NET 中有一些实用程序/功能,我可以使用这些实用程序/功能从 PNG 即时构建 .ico... 很高兴知道,寿。
  • @chaiguy 你看过使用hardcodet.net/projects/wpf-notifyicon 来做 WPF 系统托盘的东西吗?
  • @MerickOWA 这实际上是我正在使用的库 - 它的问题是它希望图标资源是 System.Drawing.Icon 并且如果不是,则会抛出异常,因此我的麻烦。
  • @chaiguy TaskBarIcon.IconSource 属性不是声明为 ImageSource 吗?

标签: c# .net wpf icons png


【解决方案1】:

你可以写

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);

【讨论】:

  • 这里完全跑题了,但祝贺主持人选举,@SLaks!
  • 这里的问题是 GetHIcon() 是 Bitmap 的一种方法,而不是 ImageSource,而且似乎没有任何理智的方法可以从 ImageSource 获取 Bitmap——我发现的一种方法(大约 20 行长)不保留 PNG 透明度。
【解决方案2】:

我在找这个~ 这是一个,但不是很好!

        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();

【讨论】:

    猜你喜欢
    • 2011-06-29
    • 1970-01-01
    • 2010-11-01
    • 2011-03-23
    • 2011-11-28
    • 1970-01-01
    • 1970-01-01
    • 2010-11-10
    • 2021-02-04
    相关资源
    最近更新 更多