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

相关推荐
SelectDB15 小时前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
荣码1 天前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
金銀銅鐵1 天前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li2 天前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸2 天前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学2 天前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田2 天前
Pydantic校验配置文件
python
hboot2 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi3 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi3 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab