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

相关推荐
天天进步20159 分钟前
从零打造 Python 全栈项目:智能教学辅助系统
开发语言·人工智能·python
带带弟弟学爬虫__27 分钟前
dyAPP数据采集-个人主页、发布、搜索、评论
服务器·python·算法·flutter·java-ee·django
还是鼠鼠30 分钟前
AI掘金头条新闻系统 (Toutiao News)-相关推荐
后端·python·mysql·fastapi·web
sali-tec33 分钟前
C# 基于OpenCv的视觉工作流-章75-线-线角度
图像处理·人工智能·opencv·算法·计算机视觉
数智工坊42 分钟前
PyCharm 运行 Python 脚本总自动进 Test 模式?附 RT-DETRv2 依赖缺失终极排坑
开发语言·ide·人工智能·python·pycharm
AI砖家1 小时前
每日一个skill:web-artifacts-builder,构建复杂 Claude.ai HTML Artifact 的生产力工具包
java·前端·人工智能·python
彦为君1 小时前
JavaSE-05-字符串(全面深入)
java·开发语言·python·ai·ai编程
Upsy-Daisy1 小时前
AI Agent 项目学习笔记(九):网页搜索、网页抓取与资源下载工具
笔记·python·学习
wj3055853781 小时前
课程 1:WSL + uv + ComfyUI 环境选择说明
python·wsl·cuda·uv·comfyui
wj3055853781 小时前
课程 2:使用 uv 安装 ComfyUI
python·uv·comfyui