如何在 C# 中创建包含多种尺寸/图像的图标文件

发布于 2024-09-08 16:21:11 字数 162 浏览 1 评论 0原文

如何创建包含多种尺寸的图标文件?

我知道我使用 Icon.FromHandle() 从位图创建图标,但如何向该图标添加另一个图像/大小?

编辑:我需要在我的应用程序中执行此操作,因此我无法执行外部应用程序来进行组合。

How do I create an icon file that contains multiple sizes?

I know that I create a icon from a bitmap using Icon.FromHandle() but how do I add another image / size to that icon?

Edit: I need to do this in my application, so I cannot execute an external application to do the combining.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

淡紫姑娘! 2024-09-15 16:21:11

我一直在寻找一种将 .png 文件(没什么花哨的)组合成图标的方法。在无法找到简单的东西并且这个问题是顶部搜索结果后,我创建了下面的代码。


如果对于每个图像,以下代码可以创建具有多种尺寸的图标 Image.RawFormatImageFormat.PngImage.PixelFormatPixelFormat.Format32bppArgb 并且尺寸小于或等于 256x256:

/// <summary>
/// Provides methods for creating icons.
/// </summary>
public class IconFactory
{

    #region constants

    /// <summary>
    /// Represents the max allowed width of an icon.
    /// </summary>
    public const int MaxIconWidth = 256;

    /// <summary>
    /// Represents the max allowed height of an icon.
    /// </summary>
    public const int MaxIconHeight = 256;

    private const ushort HeaderReserved = 0;
    private const ushort HeaderIconType = 1;
    private const byte HeaderLength = 6;

    private const byte EntryReserved = 0;
    private const byte EntryLength = 16;

    private const byte PngColorsInPalette = 0;
    private const ushort PngColorPlanes = 1;

    #endregion

    #region methods

    /// <summary>
    /// Saves the specified <see cref="Bitmap"/> objects as a single 
    /// icon into the output stream.
    /// </summary>
    /// <param name="images">The bitmaps to save as an icon.</param>
    /// <param name="stream">The output stream.</param>
    /// <remarks>
    /// The expected input for the <paramref name="images"/> parameter are 
    /// portable network graphic files that have a <see cref="Image.PixelFormat"/> 
    /// of <see cref="PixelFormat.Format32bppArgb"/> and where the
    /// width is less than or equal to <see cref="IconFactory.MaxIconWidth"/> and the 
    /// height is less than or equal to <see cref="MaxIconHeight"/>.
    /// </remarks>
    /// <exception cref="InvalidOperationException">
    /// Occurs if any of the input images do 
    /// not follow the required image format. See remarks for details.
    /// </exception>
    /// <exception cref="ArgumentNullException">
    /// Occurs if any of the arguments are null.
    /// </exception>
    public static void SavePngsAsIcon(IEnumerable<Bitmap> images, Stream stream)
    {
        if (images == null)
            throw new ArgumentNullException("images");
        if (stream == null)
            throw new ArgumentNullException("stream");

        // validates the pngs
        IconFactory.ThrowForInvalidPngs(images);

        Bitmap[] orderedImages = images.OrderBy(i => i.Width)
                                       .ThenBy(i => i.Height)
                                       .ToArray();

        using (var writer = new BinaryWriter(stream))
        {

            // write the header
            writer.Write(IconFactory.HeaderReserved);
            writer.Write(IconFactory.HeaderIconType);
            writer.Write((ushort)orderedImages.Length);

            // save the image buffers and offsets
            Dictionary<uint, byte[]> buffers = new Dictionary<uint, byte[]>();

            // tracks the length of the buffers as the iterations occur
            // and adds that to the offset of the entries
            uint lengthSum = 0;
            uint baseOffset = (uint)(IconFactory.HeaderLength +
                                     IconFactory.EntryLength * orderedImages.Length);

            for (int i = 0; i < orderedImages.Length; i++)
            {
                Bitmap image = orderedImages[i];

                // creates a byte array from an image
                byte[] buffer = IconFactory.CreateImageBuffer(image);

                // calculates what the offset of this image will be
                // in the stream
                uint offset = (baseOffset + lengthSum);

                // writes the image entry
                writer.Write(IconFactory.GetIconWidth(image));
                writer.Write(IconFactory.GetIconHeight(image));
                writer.Write(IconFactory.PngColorsInPalette);
                writer.Write(IconFactory.EntryReserved);
                writer.Write(IconFactory.PngColorPlanes);
                writer.Write((ushort)Image.GetPixelFormatSize(image.PixelFormat));
                writer.Write((uint)buffer.Length);
                writer.Write(offset);

                lengthSum += (uint)buffer.Length;

                // adds the buffer to be written at the offset
                buffers.Add(offset, buffer);
            }

            // writes the buffers for each image
            foreach (var kvp in buffers)
            {

                // seeks to the specified offset required for the image buffer
                writer.BaseStream.Seek(kvp.Key, SeekOrigin.Begin);

                // writes the buffer
                writer.Write(kvp.Value);
            }
        }

    }

    private static void ThrowForInvalidPngs(IEnumerable<Bitmap> images)
    {
        foreach (var image in images)
        {
            if (image.PixelFormat != PixelFormat.Format32bppArgb)
            {
                throw new InvalidOperationException
                    (string.Format("Required pixel format is PixelFormat.{0}.",
                                   PixelFormat.Format32bppArgb.ToString()));
            }

            if (image.RawFormat.Guid != ImageFormat.Png.Guid)
            {
                throw new InvalidOperationException
                    ("Required image format is a portable network graphic (png).");
            }

            if (image.Width > IconFactory.MaxIconWidth ||
                image.Height > IconFactory.MaxIconHeight)
            {
                throw new InvalidOperationException
                    (string.Format("Dimensions must be less than or equal to {0}x{1}",
                                   IconFactory.MaxIconWidth, 
                                   IconFactory.MaxIconHeight));
            }
        }
    }

    private static byte GetIconHeight(Bitmap image)
    {
        if (image.Height == IconFactory.MaxIconHeight)
            return 0;

        return (byte)image.Height;
    }

    private static byte GetIconWidth(Bitmap image)
    {
        if (image.Width == IconFactory.MaxIconWidth)
            return 0;

        return (byte)image.Width;
    }

    private static byte[] CreateImageBuffer(Bitmap image)
    {
        using (var stream = new MemoryStream())
        {
            image.Save(stream, image.RawFormat);

            return stream.ToArray();
        }
    }

    #endregion

}

用法:

using (var png16 = (Bitmap)Bitmap.FromFile(@"C:\Test\3dGlasses16.png"))
using (var png32 = (Bitmap)Bitmap.FromFile(@"C:\Test\3dGlasses32.png"))
using (var stream = new FileStream(@"C:\Test\Combined.ico", FileMode.Create))
{
    IconFactory.SavePngsAsIcon(new[] { png16, png32 }, stream);
}

I was looking for a way to combine .png files, nothing fancy, into an icon. I created the below code after not being able to find something simple and with this question being the top search result.


The following code can create an icon with multiple sizes if, for each of the images, the Image.RawFormat is ImageFormat.Png, the Image.PixelFormat is PixelFormat.Format32bppArgb and the dimensions are less than or equal to 256x256:

/// <summary>
/// Provides methods for creating icons.
/// </summary>
public class IconFactory
{

    #region constants

    /// <summary>
    /// Represents the max allowed width of an icon.
    /// </summary>
    public const int MaxIconWidth = 256;

    /// <summary>
    /// Represents the max allowed height of an icon.
    /// </summary>
    public const int MaxIconHeight = 256;

    private const ushort HeaderReserved = 0;
    private const ushort HeaderIconType = 1;
    private const byte HeaderLength = 6;

    private const byte EntryReserved = 0;
    private const byte EntryLength = 16;

    private const byte PngColorsInPalette = 0;
    private const ushort PngColorPlanes = 1;

    #endregion

    #region methods

    /// <summary>
    /// Saves the specified <see cref="Bitmap"/> objects as a single 
    /// icon into the output stream.
    /// </summary>
    /// <param name="images">The bitmaps to save as an icon.</param>
    /// <param name="stream">The output stream.</param>
    /// <remarks>
    /// The expected input for the <paramref name="images"/> parameter are 
    /// portable network graphic files that have a <see cref="Image.PixelFormat"/> 
    /// of <see cref="PixelFormat.Format32bppArgb"/> and where the
    /// width is less than or equal to <see cref="IconFactory.MaxIconWidth"/> and the 
    /// height is less than or equal to <see cref="MaxIconHeight"/>.
    /// </remarks>
    /// <exception cref="InvalidOperationException">
    /// Occurs if any of the input images do 
    /// not follow the required image format. See remarks for details.
    /// </exception>
    /// <exception cref="ArgumentNullException">
    /// Occurs if any of the arguments are null.
    /// </exception>
    public static void SavePngsAsIcon(IEnumerable<Bitmap> images, Stream stream)
    {
        if (images == null)
            throw new ArgumentNullException("images");
        if (stream == null)
            throw new ArgumentNullException("stream");

        // validates the pngs
        IconFactory.ThrowForInvalidPngs(images);

        Bitmap[] orderedImages = images.OrderBy(i => i.Width)
                                       .ThenBy(i => i.Height)
                                       .ToArray();

        using (var writer = new BinaryWriter(stream))
        {

            // write the header
            writer.Write(IconFactory.HeaderReserved);
            writer.Write(IconFactory.HeaderIconType);
            writer.Write((ushort)orderedImages.Length);

            // save the image buffers and offsets
            Dictionary<uint, byte[]> buffers = new Dictionary<uint, byte[]>();

            // tracks the length of the buffers as the iterations occur
            // and adds that to the offset of the entries
            uint lengthSum = 0;
            uint baseOffset = (uint)(IconFactory.HeaderLength +
                                     IconFactory.EntryLength * orderedImages.Length);

            for (int i = 0; i < orderedImages.Length; i++)
            {
                Bitmap image = orderedImages[i];

                // creates a byte array from an image
                byte[] buffer = IconFactory.CreateImageBuffer(image);

                // calculates what the offset of this image will be
                // in the stream
                uint offset = (baseOffset + lengthSum);

                // writes the image entry
                writer.Write(IconFactory.GetIconWidth(image));
                writer.Write(IconFactory.GetIconHeight(image));
                writer.Write(IconFactory.PngColorsInPalette);
                writer.Write(IconFactory.EntryReserved);
                writer.Write(IconFactory.PngColorPlanes);
                writer.Write((ushort)Image.GetPixelFormatSize(image.PixelFormat));
                writer.Write((uint)buffer.Length);
                writer.Write(offset);

                lengthSum += (uint)buffer.Length;

                // adds the buffer to be written at the offset
                buffers.Add(offset, buffer);
            }

            // writes the buffers for each image
            foreach (var kvp in buffers)
            {

                // seeks to the specified offset required for the image buffer
                writer.BaseStream.Seek(kvp.Key, SeekOrigin.Begin);

                // writes the buffer
                writer.Write(kvp.Value);
            }
        }

    }

    private static void ThrowForInvalidPngs(IEnumerable<Bitmap> images)
    {
        foreach (var image in images)
        {
            if (image.PixelFormat != PixelFormat.Format32bppArgb)
            {
                throw new InvalidOperationException
                    (string.Format("Required pixel format is PixelFormat.{0}.",
                                   PixelFormat.Format32bppArgb.ToString()));
            }

            if (image.RawFormat.Guid != ImageFormat.Png.Guid)
            {
                throw new InvalidOperationException
                    ("Required image format is a portable network graphic (png).");
            }

            if (image.Width > IconFactory.MaxIconWidth ||
                image.Height > IconFactory.MaxIconHeight)
            {
                throw new InvalidOperationException
                    (string.Format("Dimensions must be less than or equal to {0}x{1}",
                                   IconFactory.MaxIconWidth, 
                                   IconFactory.MaxIconHeight));
            }
        }
    }

    private static byte GetIconHeight(Bitmap image)
    {
        if (image.Height == IconFactory.MaxIconHeight)
            return 0;

        return (byte)image.Height;
    }

    private static byte GetIconWidth(Bitmap image)
    {
        if (image.Width == IconFactory.MaxIconWidth)
            return 0;

        return (byte)image.Width;
    }

    private static byte[] CreateImageBuffer(Bitmap image)
    {
        using (var stream = new MemoryStream())
        {
            image.Save(stream, image.RawFormat);

            return stream.ToArray();
        }
    }

    #endregion

}

Usage:

using (var png16 = (Bitmap)Bitmap.FromFile(@"C:\Test\3dGlasses16.png"))
using (var png32 = (Bitmap)Bitmap.FromFile(@"C:\Test\3dGlasses32.png"))
using (var stream = new FileStream(@"C:\Test\Combined.ico", FileMode.Create))
{
    IconFactory.SavePngsAsIcon(new[] { png16, png32 }, stream);
}
好多鱼好多余 2024-09-15 16:21:11

Quick CYA:我只是谷歌搜索了一下,还没有测试下面的方法。 YMMV。

我发现这篇文章,其中提到了一个执行此操作的类(尽管是在VB中) .Net,但很容易翻译),并讲述了他如何使用它。虽然该线程指向的页面似乎不再包含提到的源代码,但我确实找到了它的一个版本 此处。

Quick CYA: I just did a Google search, and have not tested the method below. YMMV.

I found this article, which mentions a class that does this (albeit in VB.Net, but easy enough to translate), and tells how he used it. While the page that the thread points to no longer appears to have the source code mentioned, I did find a version of it here.

青衫负雪 2024-09-15 16:21:11

这可以通过 IconLib 来完成。您可以从 CodeProject 文章获取源代码,也可以从我的 GitHub 镜像获取编译后的 dll

public void Convert(string pngPath, string icoPath)
{
    MultiIcon mIcon = new MultiIcon();
    mIcon.Add("Untitled").CreateFrom(pngPath, IconOutputFormat.FromWin95);
    mIcon.SelectedIndex = 0;
    mIcon.Save(icoPath, MultiIconFormat.ICO);
}

CreateFrom 可以采用 256x256 png 或 System.Drawing.Bitmap 对象的路径。

This can be done with IconLib. You can get the source from the CodeProject article or you can get a compiled dll from my GitHub mirror.

public void Convert(string pngPath, string icoPath)
{
    MultiIcon mIcon = new MultiIcon();
    mIcon.Add("Untitled").CreateFrom(pngPath, IconOutputFormat.FromWin95);
    mIcon.SelectedIndex = 0;
    mIcon.Save(icoPath, MultiIconFormat.ICO);
}

CreateFrom can take either the path to a 256x256 png or a System.Drawing.Bitmap object.

來不及說愛妳 2024-09-15 16:21:11

您无法使用 System.Drawing API 创建图标。它们是为访问图标文件中的特定图标而构建的,而不是为了将多个图标写回到 .ico 文件中。

如果您只想制作图标,您可以使用 GIMP 或其他图像处理程序来创建 .ico 文件。否则,如果您确实需要以编程方式制作 .ico 文件,您可以使用 png2ico (调用使用 System.Diagnostics.Process.Start )或类似的东西。

You can't create an icon using the System.Drawing APIs. They were built for accessing specific icons from within an icon file, but not for writing back multiple icons to an .ico file.

If you are just wanting to make icons, you could use GIMP or another image processing program to create your .ico files. Otherwise if you really need to make the .ico files programatically, you could use png2ico (invoking using System.Diagnostics.Process.Start) or something similar.

左耳近心 2024-09-15 16:21:11

使用IcoFX:http://icofx.ro/

它可以创建Windows图标并在1个ico中存储多种尺寸和颜色文件

Use IcoFX: http://icofx.ro/

It can create Windows icons and store multiple sizes and colors in 1 ico file

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文