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

相关推荐
用户70887690393813 小时前
给传统 SaaS 增加 AI 能力:3个真实落地场景
python
卷无止境13 小时前
FastAPI中间件全解析:请求处理链条上的隐形关卡
后端·python·fastapi
用户03321266636713 小时前
使用 Python 将 HTML 内容添加到 PowerPoint 演示文稿中
python·html
看浪的路人13 小时前
第4讲:MCP Client 开发——连接、发现、调用
windows·python·ai
Swift社区13 小时前
Python 开发环境怎么选?PyCharm、VS Code、Trae 谁更适合 AI 开发?
人工智能·python·pycharm
卷无止境13 小时前
聊聊Web开发里的流式数据 从原理到FastAPI实战
后端·python·fastapi
SMF191913 小时前
【PyCharm】让 PyCharm 使用 .venv 虚拟环境
ide·python·pycharm
修远客13 小时前
感知模块:Agent的眼睛和耳朵 — 三层降级策略让Agent永不"失明"
python·agent
circuitsosk14 小时前
Prompt Engineering进阶:面向复杂业务场景的模板化管理与动态注入策略
python·langchain·prompt·跨境电商·rag·上下文管理·动态注入
3A Cloud14 小时前
使用 iThinkAir 将“摄影级人像生图”Skill 开发成应用
图像处理·人工智能