【发布时间】:2014-06-05 11:40:28
【问题描述】:
我有很多小的 png,我想将它们组合成一个 png 文件,我使用 python 来完成这项工作,这是我的代码:
from PIL import Image,ImageDraw
import os,math
def combine_images(path,out,padding=1):
imgs=[]
min_width,max_width,min_height,max_height=-1,-1,-1,-1
for infile in os.listdir(path):
f,ext=os.path.splitext(infile)
if ext== ".png":
im=Image.open(os.path.join(path,infile))
imgs.append(im)
min_width = im.size[0] if min_width<0 else min(min_width,im.size[0])
max_width = im.size[0] if max_width<0 else max(max_width,im.size[0])
min_height = im.size[1] if min_height<0 else min(min_height,im.size[0])
max_height = im.size[1] if max_height<0 else max(max_height,im.size[0])
#calculate the column and rows
num = len(imgs)
column_f = math.ceil(math.sqrt(num))
row_f = math.ceil(num / column_f)
column = int(column_f)
row = int(row_f)
#out image
box=(max_width + padding*2,max_height + padding*2)
out_width = row * box[0]
out_height = column * box[1]
//out_image=Image.new('L', (out_width,out_height), color=transparent)
out_image=Image.new("RGB", (out_width, out_height))
for y in range(row):
for x in range(column):
index = (y * column) + x
if index < num:
out_image.paste(imgs[index],(x * box[0],y * box[1]))
out_image.save(out)
combine_images('icon','t.png')
逻辑很简单,读取某个目录下的png,计算图片的个数、大小,然后新建一张图片,一张一张粘贴。额外计算用于使结果图像尽可能正方形。
然而这是我得到的:http://pbrd.co/1kzErSc
我遇到两个问题:
1 我无法使输出的图像透明。
2 看来我的图标布局会浪费图片太多空间。
我想知道是否可以修复它?
【问题讨论】:
标签: python python-imaging-library