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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/1196155.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

下载适合内网服务器环境的python whl安装包

1、第三方包whl下载地址&#xff1a; https://pypi.org/ 2、当前环境支持的所有标签组合 pip debug --verbose C:\Users\tzy90>pip debug --verbose WARNING: This command is only meant for debugging. Do not use this with automation for parsing and getting these d…

深入解析:嵌入式第二十三篇——数据结构基本概念

深入解析:嵌入式第二十三篇——数据结构基本概念2026-01-21 20:07 tlnshuju 阅读(0) 评论(0) 收藏 举报pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; displa…

内网服务器环境如何进行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] │ …

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

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

2026成都最新房屋装修品牌top5评测!服务深度覆盖金牛区、新都区、青羊区、成华区等地优质装修公司权威榜单发布,品质赋能构筑理想家居生活.

随着人们对居住品质要求的不断提升,房屋装修市场呈现出多元化、个性化的发展趋势。本榜单基于环保标准、设计实力、施工工艺、服务覆盖、客户口碑五大维度(四川大晶装饰新增“晶钻体系”专项维度),结合行业协会数据…

提示工程架构师最新趋势:AI辅助的提示词自动化生成与准确性保障

提示工程架构师最新趋势:AI辅助的提示词自动化生成与准确性保障 一、引言 (Introduction) 钩子 (The Hook) 你是否曾在使用人工智能模型时,为了想出一个能得到理想输出的提示词而绞尽脑汁?比如,当你希望通过图像生成模型创作一幅独特的艺术作品,或者利用语言模型撰写一…

MongoDB 7.0 副本集高可用部署

适用场景:生产环境搭建高可用 MongoDB 副本集,确保数据冗余与自动故障转移 MongoDB 版本:7.0.28(社区版) 操作系统:CentOS 7 架构:1 主(Primary) + 2 从(Secondary),共 3 个数据承载节点(P-S-S) 存储引擎…

基于深度学习的密集人群行人检测系统演示与介绍(YOLOv12/v11/v8/v5模型+Pyqt5界面+训练代码+数据集)

摘要:本文介绍了一套基于YOLO系列算法的密集人群行人检测系统。系统支持图片、视频及实时摄像头检测,具备模型切换、置信度调节、数据统计与导出等功能。通过对比YOLOv5/v8/v11/v12模型性能,显示YOLO12n精度最高(mA…

0117模考

考时 开场1h纯在chatting with friends,1h后才开始写题。 开T1,这不是MST+倍增板子吗,直接写写写,调了几发,在10:40交了。 T2看了是个状压dp板子,感觉比较难写(之后发现代码只有1k),先看T3。 T3看了十分钟有了思…

ps命令

ps命令下面给你一组“更全、更强”的命令组合,用于 Kafka 进程性能分析。你可以把它们当作一套排查脚本:从线程、CPU、IO、网络、GC、JVM 堆、以及系统层面逐层分析。 我会按从轻量到重型排序,并且说明每条命令的用…

Docker 镜像启动失败时,如何用 --entrypoint 进入容器排障

# Docker 镜像启动即退出?使用 --entrypoint /bin/bash 进入容器排障 在日常使用 Docker 的过程中,经常会遇到这样一种情况: > 镜像可以正常 build > 但 `docker run` 一启动就退出 > 容器根本进不去,日…

打破屏幕的边界:实战 MCP 协议对接 Slack 与 Telegram,构建 7*24 小时随身待命的 AI 智能指挥中心

&#x1f680; 打破屏幕的边界&#xff1a;实战 MCP 协议对接 Slack 与 Telegram&#xff0c;构建 7*24 小时随身待命的 AI 智能指挥中心 &#x1f4a1; 内容摘要 (Abstract) 在移动办公与分布式协作成为主流的今天&#xff0c;交互的“即时性”与“无处不在”是提升生产力的…

使用natapp实现内网穿透

1、由于在开发的时候需要接微信支付、支付宝支付等其他接口的时候,需要线上回调,这在本地开发测试的比较麻烦,所以就使用natapp内网穿透工具实现远程接口可以直接回调到本地 2、安装:#由于我是使用的linux环境,所…

含贵金属六元合金详解:成分、应用及本地合规回收攻略

在贵金属合金领域,六元合金因兼具多种贵金属的优异性能,成为电子、化工、航空航天等高端行业的核心材料,同时也是工业废料中极具回收价值的“隐形宝库”。本文结合本地行业实操经验,全面拆解含贵金属六元合金的成分…

【C++】网络编程 - hjk

前言 围绕Socket 的基础概念、I/O 模型,逐步实现阻塞 I/O 客户端 - 服务器、多进程 / 多线程服务端处理,以及基于 select、poll、epoll 的 I/O 多路复用服务端,侧重与如何实现。 什么是socket 在C++中,Socket编程是…

京东e卡回收,秒变实用零钱

不少人手里都攒着闲置的京东e卡,想把它们换成能随手花的日常零钱。就说楼下的张阿姨吧,去年她收到两张面值五百的京东e卡,可她平时很少在京东购物,便琢磨着换成零钱给孙子买零食、给老伴买茶。她跑了两家线下礼品回…

Oracle 迁移至 KingbaseES 实战指南(最佳实践)

Oracle 迁移至 KingbaseES 实战指南&#xff08;最佳实践&#xff09; 随着国产数据库生态逐步成熟&#xff0c;越来越多企业开始将核心业务系统从 Oracle 等商业数据库迁移至国产数据库平台。其中&#xff0c;KingbaseES 作为国产关系型数据库中对 Oracle 兼容度较高的产品之…

day7 454.383.15.18

day7 454.383.15.18Leetcode 454 四数相加Ⅱ unordered_map使用的练习,一次通过,但是定义了两个unordered_map,并且需要经过两次遍历,空间和时间消耗都增加了 int fourSumCount(vector<int>& nums1, vec…

使用 Python 将 PowerPoint 转换为 Word 文档 - 详解

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

SDK location not found. Define a valid SDK location with an ANDROID_HOME environment variable or by

Android React Native 异常处理 异常信息 FAILURE: Build failed with an exception.* Where: Build file D:\Git\Tencent\odin-client\android\build.gradle line: 25* What went wrong: A problem occurred evaluating root project odin-client. > Failed to apply plu…