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等参数,改变图标和蒙版的形状和位置等。

相关推荐
ikun_文2 小时前
Django框架路由Router的使用
python·pycharm·django
IvanCodes2 小时前
Python 基础语法(二):字符串与常用操作
python
昭昭日月明2 小时前
LangChain 生态:从链到代理,开发者需要掌握的三大核心
python·langchain·agent
Csvn2 小时前
🐍 Day 8:面向对象编程
后端·python
程序员天天困2 小时前
向量检索不准怎么办:混合检索与 Rerank 重排序召回优化实战
后端·python·ai编程
alphaTao4 小时前
LeetCode 每日一题 2026/8/24-2026/8/30
python·算法·leetcode
苏灿烤鱼4 小时前
当 AI Agent 遇见真实科学环境:深度拆解 Scientific Agent Skills,把"聊天机器人"变成"AI 科学家"
python·开源·agent
张文君4 小时前
ubuntu26.04坏道坏块分区隔离急速版260831-V0.12
linux·python
lupai15 小时前
手机在网状态接口实测效果与质量评估
大数据·python·智能手机·api接口
hahaha601615 小时前
HLS高层次综合设计技巧--C++类和模板
图像处理·人工智能·算法·计算机视觉