2017-08-31 87 views
1

我編寫的這個程序需要一張圖像並將其裁剪成7個各種尺寸的PNG圖像。如何使用PIL保存多尺寸圖標

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輸出一個具有指定大小而不是多個PNG輸出的單個ICO文件。

回答

0

作爲輸入圖像重複相同的圖標:

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

si zes

包含在此ico文件中的大小列表;這些是2元組,(width, height);默認爲[(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (255, 255)]。任何大於原始尺寸或255的尺寸都將被忽略。

其實在這些文檔中有一個輸入錯誤(我將修復); default includes (256, 256),而不是(255,255)。所以默認值符合您的要求,您可以只是imgc.save('out.ico')節省:

from PIL import Image 

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

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

imgc.save('out.ico') 
+0

感謝您的時間,但我使用的圖片是不一樣的形象打了折扣,每一個被設計成最適合每個分辨率的網格。 https://imgur.com/a/BfRec只裁剪第一個,縮小它對我來說不起作用。 – arch129