PNG转ICO后图标拉伸变形,如何保持原图像比例?
解决PNG转ICO时的拉伸变形问题
你的问题出在两个核心点:
resize方法不会直接修改原图像,而是返回新的图像对象,你未接收这个返回值,导致原图根本没被调整- ICO格式要求图标为正方形,直接强制拉伸非正方形图像必然导致变形,必须先按原比例将图像处理成正方形(裁剪多余区域或填充背景)
方案1:裁剪多余区域,得到正方形图像
若图像主体在中心,适合用裁剪方式保留核心内容:
from PIL import Image # 打开原图 png = Image.open("converter.png") width, height = png.size # 取宽高中的较小值作为正方形边长 side = min(width, height) # 计算居中裁剪的坐标 left = (width - side) // 2 top = (height - side) // 2 right = left + side bottom = top + side # 裁剪为正方形并调整到ICO常用尺寸 square_img = png.crop((left, top, right, bottom)) square_img = square_img.resize((64, 64), resample=Image.Resampling.LANCZOS) # 保存ICO格式 square_img.save("icon.ico", format='ICO')
方案2:填充背景,保留完整图像
若不想裁剪图像,可在空白区域填充背景色(支持透明):
from PIL import Image png = Image.open("converter.png") width, height = png.size side = max(width, height) # 创建正方形透明画布,需不透明可替换为(255,255,255)等颜色值 square_img = Image.new("RGBA", (side, side), (0, 0, 0, 0)) # 计算居中粘贴的位置 paste_x = (side - width) // 2 paste_y = (side - height) // 2 square_img.paste(png, (paste_x, paste_y)) # 调整尺寸并保存 square_img = square_img.resize((64, 64), resample=Image.Resampling.LANCZOS) square_img.save("icon.ico", format='ICO')
补充优化建议
- 保存ICO时无需指定
quality参数,该参数对ICO格式无效 - 建议生成包含多尺寸的ICO文件,系统会根据场景自动适配,只需添加
sizes参数:square_img.save("icon.ico", format='ICO', sizes=[(16,16), (32,32), (64,64), (256,256)])
内容的提问来源于stack exchange,提问作者Forty966699669
相关产品推荐
相关产品推荐

