欢迎访问!
您的支持是我们不断前行的动力!

C# PNG图片转ICON图标

注意:传入的PNG格式需要长宽相等,size数值可根据原始图片的尺寸进行调整

private static bool ConvertPNGToIcon(string inputPath, string outputPath, int size = 512, bool preserveAspectRatio = true)
{
    using (FileStream inputStream = new FileStream(inputPath, FileMode.Open))
    using (FileStream outputStream = new FileStream(outputPath, FileMode.OpenOrCreate))
    {
        return ConvertToIcon(inputStream, outputStream, size, preserveAspectRatio);
    }
}
private static bool ConvertToIcon(Stream input, Stream output, int size = 16, bool preserveAspectRatio = false)
{
    Bitmap inputBitmap = (Bitmap)Bitmap.FromStream(input);
    if (inputBitmap != null)
    {
        int width, height;
        if (preserveAspectRatio)
        {
            width = size;
            height = (inputBitmap.Height + 1) / inputBitmap.Width * size;
        }
        else
        {
            width = height = size;
        }
        Bitmap newBitmap = new Bitmap(inputBitmap, new System.Drawing.Size(width, height));
        if (newBitmap != null)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                newBitmap.Save(memoryStream, ImageFormat.Png);
                BinaryWriter iconWriter = new BinaryWriter(output);
                if (output != null && iconWriter != null)
                {
                    iconWriter.Write((byte)0);
                    iconWriter.Write((byte)0);
                    iconWriter.Write((short)1);
                    iconWriter.Write((short)1);
                    iconWriter.Write((byte)width);
                    iconWriter.Write((byte)height);
                    iconWriter.Write((byte)0);
                    iconWriter.Write((byte)0);
                    iconWriter.Write((short)0);
                    iconWriter.Write((short)32);
                    iconWriter.Write((int)memoryStream.Length);
                    iconWriter.Write((int)(6 + 16));
                    iconWriter.Write(memoryStream.ToArray());
                    iconWriter.Flush();
                    return true;
                }
            }
        }
        return false;
    }
    return false;
}

 

赞(0) 打赏
转载请注明出处,未注明出处不得转载,蜘蛛侠 » C# PNG图片转ICON图标
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

蜘蛛侠,您身边的爬虫专家!

觉得文章有用就打赏一下文章作者吧

支付宝扫一扫打赏

微信扫一扫打赏