如何用PIL保存多尺寸图标

2024-06-01 01:48:30 发布

您现在位置:Python中文网/ 问答频道 /正文

这个程序我写了一个单一的图像,并裁剪成7个不同大小的单独的PNG图像。在

import Image
img = Image.open("0.png")

ax1 = 0
ax2 = 0
ay1 = 0
ay2 = 0
incr = 0
last = 0
sizes = [256,128,64,48,32,24,16]

def cropicon (newsize):
    global ax1, ax2, ay2, imgc, last, incr
    incr += 1
    ax1 = ax1 + last
    ax2 = ax1 + newsize
    ay2 = newsize
    imgc = img.crop((ax1, ay1, ax2, ay2))
    imgc.save("%d.png" % incr)
    last = newsize

for size in sizes:
    cropicon(size)

Example of an input image I'm using.

我目前正在使用另一个程序来获取单独的png并将它们合并到一个ICO文件中。在

我想要的是Python输出一个具有所有指定大小的ICO文件,而不是输出多个png。在


Tags: 图像image程序imgpnglastsizesincr
1条回答
网友
1楼 · 发布于 2024-06-01 01:48:30

当输入图像重复相同的图标时:

Input image, with a large icon, then a smaller one to the right, and so on, with seven in total

然后裁剪第一个,使用sizes参数创建图标:

from PIL import Image

size_tuples = [(256, 256),
               (128, 128),
               (64, 64),
               (48, 48),
               (32, 32),
               (24, 24),
               (16, 16)]

img = Image.open("0.png")

imgc = img.crop((0, 0, 256, 256))

imgc.save('out.ico', sizes=size_tuples)

请参见docs

sizes

A list of sizes including in this ico file; these are a 2-tuple, (width, height); Default to [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (255, 255)]. Any sizes bigger than the original size or 255 will be ignored.

实际上,这些文档中有一个错误(我会修复的)default includes (256, 256),而不是(255255)。因此,默认值符合您的要求,您只需使用imgc.save('out.ico')保存:

^{pr2}$

相关问题 更多 >