news 2026/5/1 9:09:41

Web开发:使用C#的System.Drawing.Common将png图片转化为icon图片

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Web开发:使用C#的System.Drawing.Common将png图片转化为icon图片

1.安装第三方库

我的是.NET6,因此需要安装8.0.0版本的【System.Drawing.Common】,若版本太高会在.NET6平台跑不了

2.代码

using System; using System.Drawing; using System.Drawing.Imaging; using System.IO; namespace PngToIcoConverter { class Program { static void Main(string[] args) { // 你的PNG和ICO文件路径 string pngFilePath = @"F:\C_program\MSSQLBackUpTools\WinFormsApp1\WinFormsApp1\pics\backup.png"; string icoOutputPath = @"F:\C_program\MSSQLBackUpTools\WinFormsApp1\WinFormsApp1\pics\backup.ico"; try { // 调用转换方法 ConvertPngToIco(pngFilePath, icoOutputPath); Console.WriteLine("PNG转换为ICO成功!"); } catch (FileNotFoundException ex) { Console.WriteLine($"错误:找不到文件 - {ex.Message}"); } catch (IOException ex) { Console.WriteLine($"文件操作错误:{ex.Message}"); } catch (Exception ex) { Console.WriteLine($"转换失败:{ex.Message}"); } } /// <summary> /// 将PNG图片转换为ICO图标(包含多尺寸:16x16, 32x32, 48x48) /// </summary> /// <param name="pngPath">PNG文件路径</param> /// <param name="icoPath">ICO输出路径</param> public static void ConvertPngToIco(string pngPath, string icoPath) { // 验证输入文件是否存在 if (!File.Exists(pngPath)) { throw new FileNotFoundException("PNG源文件不存在", pngPath); } // 读取PNG图片 using (Bitmap pngBitmap = new Bitmap(pngPath)) { // 定义ICO需要的256尺寸 int[] icoSizes = new[] { 256 }; using (MemoryStream ms = new MemoryStream()) { // 创建ICO文件的编码器 IconEncoder encoder = new IconEncoder(); foreach (int size in icoSizes) { // 缩放图片到指定尺寸(保持比例) using (Bitmap sizedBitmap = ResizeBitmap(pngBitmap, size, size)) { encoder.AddFrame(sizedBitmap); } } // 将ICO数据写入文件 encoder.Save(ms); File.WriteAllBytes(icoPath, ms.ToArray()); } } } /// <summary> /// 缩放Bitmap到指定尺寸(保持宽高比,居中裁剪) /// </summary> private static Bitmap ResizeBitmap(Bitmap original, int width, int height) { Bitmap resized = new Bitmap(width, height); using (Graphics g = Graphics.FromImage(resized)) { // 高质量缩放设置 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; // 计算居中绘制的位置 float scale = Math.Max((float)width / original.Width, (float)height / original.Height); int newWidth = (int)(original.Width * scale); int newHeight = (int)(original.Height * scale); int x = (width - newWidth) / 2; int y = (height - newHeight) / 2; g.Clear(Color.Transparent); // 保留透明背景 g.DrawImage(original, x, y, newWidth, newHeight); } return resized; } } // 辅助类:用于生成多尺寸ICO文件 public class IconEncoder : IDisposable { private MemoryStream _stream = new MemoryStream(); private BinaryWriter _writer; private int _imageCount = 0; private List<byte[]> _imageData = new List<byte[]>(); public IconEncoder() { _writer = new BinaryWriter(_stream); } public void AddFrame(Bitmap bitmap) { if (bitmap.Width > 256 || bitmap.Height > 256) throw new ArgumentException("图标尺寸不能超过256x256"); _imageCount++; using (MemoryStream ms = new MemoryStream()) { bitmap.Save(ms, ImageFormat.Png); _imageData.Add(ms.ToArray()); } } public void Save(Stream stream) { // 写入ICO文件头 _writer.Write((short)0); // 保留 _writer.Write((short)1); // ICO类型 _writer.Write((short)_imageCount); // 图像数量 long offset = 6 + 16 * _imageCount; for (int i = 0; i < _imageCount; i++) { byte[] data = _imageData[i]; int width = data.Length > 0 ? new Bitmap(new MemoryStream(data)).Width : 0; int height = data.Length > 0 ? new Bitmap(new MemoryStream(data)).Height : 0; _writer.Write((byte)(width == 256 ? 0 : width)); _writer.Write((byte)(height == 256 ? 0 : height)); _writer.Write((byte)0); // 颜色数(0表示真彩色) _writer.Write((byte)0); // 保留 _writer.Write((short)1); // 调色板 _writer.Write((short)32); // 位深度 _writer.Write(data.Length); // 图像数据大小 _writer.Write((int)offset); // 图像数据偏移量 offset += data.Length; } foreach (byte[] data in _imageData) { _writer.Write(data); } _stream.Seek(0, SeekOrigin.Begin); _stream.CopyTo(stream); } public void Dispose() { _writer?.Dispose(); _stream?.Dispose(); } } }

3.Winform嵌入Icon

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/5/1 4:43:59

医疗联邦学习用Horovod加速训练

&#x1f4dd; 博客主页&#xff1a;jaxzheng的CSDN主页 医疗联邦学习的加速革命&#xff1a;Horovod驱动的分布式训练优化 目录 医疗联邦学习的加速革命&#xff1a;Horovod驱动的分布式训练优化 引言&#xff1a;数据孤岛与通信瓶颈的双重挑战 核心维度一&#xff1a;技术应用…

作者头像 李华
网站建设 2026/4/16 16:48:51

【光伏、风力、电池】基于准对立气味代理优化(QOBL-SAO)莱维飞行变体(LFQOBL-SAO)算法的光伏、风力、电池系统优化应用研究附Matlab代码

✅作者简介&#xff1a;热爱科研的Matlab仿真开发者&#xff0c;擅长数据处理、建模仿真、程序设计、完整代码获取、论文复现及科研仿真。&#x1f34e; 往期回顾关注个人主页&#xff1a;Matlab科研工作室&#x1f34a;个人信条&#xff1a;格物致知,完整Matlab代码及仿真咨询…

作者头像 李华
网站建设 2026/4/17 20:21:24

【机器人路径规划】基于四种最新算法(小龙虾优化算法COA、螳螂搜索算法MSA、红尾鹰算法RTH、霸王龙优化算法TROA)求解机器人路径规划研究附Matlab代码

✅作者简介&#xff1a;热爱科研的Matlab仿真开发者&#xff0c;擅长数据处理、建模仿真、程序设计、完整代码获取、论文复现及科研仿真。 &#x1f34e; 往期回顾关注个人主页&#xff1a;Matlab科研工作室 &#x1f34a;个人信条&#xff1a;格物致知,完整Matlab代码及仿真…

作者头像 李华
网站建设 2026/5/1 8:44:00

内网服务器环境如何进行python依赖安装

使用命令查询本地包依赖&#xff1a;pipdeptree ├── requests [required: >2.31.0,<3.0.0, installed: 2.31.0] │ ├── certifi [required: >2017.4.17, installed: 2024.2.2] │ ├── charset-normalizer [required: >2,<4, installed: 3.3.2] │ …

作者头像 李华
网站建设 2026/5/1 2:02:36

AI时代下的DBA、写作、学习和未来.md

AI率&#xff1a;本篇文章AI率约50%&#xff0c;与AI battle回合约30次 推荐理由&#xff1a;有一些对AI ops的思考和洞察&#xff0c;所以推荐 AI时代的写作 AI对写博客、写公众号的作者来说&#xff0c;可能是一个致命的打击&#xff0c;因为AI写作实在是太简单。因为我自己…

作者头像 李华