
pillow 的 `sizes` 参数在保存 ico 文件时并非直接强制使用指定尺寸,而是基于源图像长宽比进行等比缩放,导致实际生成的图标尺寸与预期不符;解决方法是确保输入图像是正方形,或预先缩放/填充为所需最大尺寸。
在使用 Pillow(v10.2.0+)生成多尺寸 ICO 图标时,开发者常误以为传入 sizes=[(16,16), (24,24), ..., (256,256)] 就能精确生成对应像素尺寸的图标条目。但实际行为是:Pillow 会对原始图像按比例缩放以适配每个目标尺寸,同时保持宽高比不变。因此,若原始图像非正方形(如常见的 256×244 PNG),缩放后得到的尺寸将不是整数对,而是近似值(如 (16, 15)、(24, 23)),正如你输出中 {'sizes': {(96, 91), (48, 46), ...}} 所示。
✅ 正确做法:预处理图像为正方形
ICO 格式规范要求各尺寸图标均为正方形,且 Windows 资源加载器也严格依赖此约定。Pillow 在内部调用缩放逻辑时,会以源图的最小边长为基准做等比缩放,从而导致非正方形输入必然产生非整数宽高比的输出。
以下为推荐的健壮实现:
from PIL import Image
from io import BytesIO
def create_ico_from_image(
data: bytes,
sizes: list[tuple[int, int]] = [
(16, 16), (24, 24), (32, 32), (48, 48),
(64, 64), (96, 96), (128, 128), (192, 192), (256, 256)
],
fill_color: tuple[int, int, int] = (255, 255, 255) # 透明背景建议用 (0,0,0,0),需转 RGBA
) -> bytes:
with Image.open(BytesIO(data)) as img:
# 1. 转换为 RGBA(保留透明度)
if img.mode != "RGBA":
img = img.convert("RGBA")
# 2. 获取最大目标尺寸,用于裁剪/填充基准
max_size = max(max(s) for s in sizes)
# 3. 等比缩放到最大尺寸,再居中裁剪为正方形(推荐用于摄影类图)
# 或:填充为正方形(推荐用于 Logo/图标类图)
img_square = Image.new("RGBA", (max_size, max_size), fill_color)
img_ratio = min(max_size / img.width, max_size / img.height)
new_size = (int(img.width * img_ratio), int(img.height * img_ratio))
img_resized = img.resize(new_size, Image.LANCZOS)
# 居中粘贴到正方形画布
offset = ((max_size - new_size[0]) // 2, (max_size - new_size[1]) // 2)
img_square.paste(img_resized, offset, img_resized) # 第三个参数启用 alpha 遮罩
# 4. 保存为 ICO,指定 sizes
output = BytesIO()
img_square.save(output, format="ICO", sizes=sizes, bitmap_format="bmp")
return output.getvalue()
# 使用示例
with open(r"c:\path\to\image.png", "rb") as f:
ico_data = create_ico_from_image(f.read())
with open(r"c:\path\to\output.ico", "wb") as f:
f.write(ico_data)⚠️ 注意事项
bitmap_format="bmp" 是必须的:Windows ICO 解析器最兼容 BMP 子图像格式;省略可能导致部分尺寸丢失或显示异常。
避免 quality=100 和 subsampling=0:这些参数对 ICO 无效(仅 JPEG/WebP 支持),Pillow 会静默忽略,无需传递。
-
验证输出:可用命令行工具确认结果:
# ImageMagick(推荐) identify -format "%wx%h\n" output.ico # 或 Python 中检查 with Image.open("output.ico") as ico: print(ico.info.get("sizes", set())) 透明度支持:确保源图含 Alpha 通道,并使用 "RGBA" 模式 + paste(..., mask=img) 实现无损透明边缘。
✅ 总结
Pillow 的 ICO sizes 参数本质是“生成一组按比例缩放的正方形图标”,而非“强行拉伸/裁剪至指定尺寸”。要获得精确 (N, N) 尺寸输出,唯一可靠方式是确保输入图像是正方形。通过预处理(缩放+填充/裁剪)统一输入形态,即可完全控制最终 ICO 中每个图标的宽高值,无需依赖外部 DLL 或 C# 工具——纯 Python 即可达成专业级图标生成效果。










