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

标签 c# bitmap icons

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

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

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

最佳答案

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


如果对于每个图像,Image.RawFormat,下面的代码可以创建一个具有多种尺寸的图标。是ImageFormat.Png , Image.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);
}

关于c# - 如何在 C# 中创建包含多种尺寸/图像的图标文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3213999/

相关文章:

c# - 使用 Entity Framework 从 2 个表返回数据

c# - 影响相对文件路径的环境 PATH 变量

复制 exif 标签时出现 Android NullPointerException

c# - 在 WPF 图像中显示图标

css - Material-Table:样式覆盖了所有自定义和 Material UI 样式以及未呈现的图标

c# - 直接从sql数据库在网页中显示pdf文件,无需将它们保存到服务器文件系统

c# - 为什么 Visual Studio 在 C# 文本编辑器中使单词 'String' 变暗

android - 通过android内置相机拍摄图像,但不保存

java - Android:如何以编程方式仅圆位图的顶角?

Django - Python help_text 作为可点击的图标