PNG转ico图标(支持圆角矩形/方形+透明背景)Python脚本 - 随笔

摘要

在网站开发或应用程序设计中,常需将高品质PNG图像转换为ICO格式图标。本文提供一份基于Pillow库实现的,能够完美保留透明背景且支持导出圆角矩形/方形图标的格式转换脚本。

源码示例

圆角方形

python 复制代码
from PIL import Image, ImageDraw, ImageOps

def create_rounded_png(image_path, output_path, size, corner_radius):
    """
    将指定的图片文件转换为n*n的圆角PNG图片。

    :param image_path: 输入图片文件的路径
    :param output_path: 输出PNG文件的路径
    :param size: 图标的大小,n*n
    :param corner_radius: 圆角的半径
    """
    with Image.open(image_path) as img:
        # 调整图片大小到n*n
        resized_img = img.resize((size, size), Image.ANTIALIAS)
        
        # 创建一个与原图大小相同的透明背景图片用于绘制圆角蒙版
        mask = Image.new('L', (size, size), 0)
        draw = ImageDraw.Draw(mask)
        
        # 绘制圆角矩形蒙版
        draw.rounded_rectangle([(0, 0), (size - 1, size - 1)], corner_radius, fill=255)
        
        # 应用圆角蒙版到原图上
        rounded_img = ImageOps.fit(resized_img, mask.size, centering=(0.5, 0.5))
        rounded_img.putalpha(mask)
        
        # 保存为PNG文件
        rounded_img.save(output_path)

# 示例用法
create_rounded_png('path/to/your/PNG_img.png', 'path/to/your/ico_file.ico', 512, 69)

任意 宽×高 圆角矩形

python 复制代码
from PIL import Image, ImageDraw, ImageOps

def create_rounded_icon(image_path, output_path, size, corner_radius):
    """
    将指定的图片文件转换为指定尺寸的圆角矩形ICO图标。

    :param image_path: 输入图片文件的路径
    :param output_path: 输出ICO文件的路径
    :param size: 图标的大小,格式为(width, height)
    :param corner_radius: 圆角的半径
    """
    with Image.open(image_path) as img:
        # 调整图片大小到指定尺寸
        resized_img = img.resize(size, Image.ANTIALIAS)
        
        # 创建一个与原图大小相同的透明背景图片用于绘制圆角蒙版
        mask = Image.new('L', size, 0)
        draw = ImageDraw.Draw(mask)
        
        # 绘制圆角矩形蒙版
        draw.rounded_rectangle([(0, 0), (size[0] - 1, size[1] - 1)], corner_radius, fill=255)
        
        # 应用圆角蒙版到原图上
        rounded_img = ImageOps.fit(resized_img, mask.size, centering=(0.5, 0.5))
        rounded_img.putalpha(mask)
        
        # 保存为ICO文件
        rounded_img.save(output_path, format='ICO')

# 示例用法
create_rounded_icon('path/to/your/PNG_img.png', 
					'path/to/your/rounded_icon.ico', 
					(512, 256), 69)

实际操作中可根据自己的需求调整size, corner_radius等参数,改变图标和蒙版的形状和位置等。

相关推荐
smj2302_796826521 小时前
解决leetcode第3911题.移除子数组元素后第k小偶数
数据结构·python·算法·leetcode
阿正呀2 小时前
Redis怎样实现本地缓存的高效失效通知
jvm·数据库·python
2501_901200532 小时前
mysql如何设置InnoDB引擎参数_优化innodb_buffer_pool
jvm·数据库·python
_.Switch2 小时前
东方财富股票数据JS逆向:secids字段和AES加密实战
开发语言·前端·javascript·网络·爬虫·python·ecmascript
Mr_sst2 小时前
Claude Code 部署与使用保姆级教程(2026 最新)
python·ai
瞎某某Blinder2 小时前
DFT学习记录[6]基于 HES06的能带计算+有效质量计算
python·学习·程序人生·数据挖掘·云计算·学习方法
m0_495496413 小时前
mysql处理复杂SQL性能_InnoDB优化器与MyISAM差异
jvm·数据库·python
forEverPlume4 小时前
PHP怎么使用Eloquent Attribute Composition属性组合_Laravel通过组合构建复杂属性【方法】
jvm·数据库·python
Aleeeeex4 小时前
RAG 那点事:从 8 份企业文档到能用的问答系统,全过程拆给你看
人工智能·python·ai编程
2301_809204704 小时前
mysql在docker容器中如何部署_利用docker-compose快速启动
jvm·数据库·python