摘要
在网站开发或应用程序设计中,常需将高品质PNG图像转换为ICO格式图标。本文提供一份基于Pillow库实现的,能够完美保留透明背景且支持导出圆角矩形/方形图标的格式转换脚本。
源码示例
圆角方形
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)
任意 宽×高 圆角矩形
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
等参数,改变图标和蒙版的形状和位置等。