Python 使用PIL将多个png合并为单个透明png
我有很多小png,我想将它们组合成一个png文件,我使用python来完成这项工作,这是我的代码:Python 使用PIL将多个png合并为单个透明png,python,python-imaging-library,Python,Python Imaging Library,我有很多小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):
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')
从PIL导入图像,ImageDraw
导入操作系统、数学
def组合_图像(路径、输出、填充=1):
imgs=[]
最小宽度,最大宽度,最小高度,最大高度=-1,-1,-1
对于os.listdir(路径)中的填充:
f、 ext=os.path.splitext(内嵌)
如果ext==“.png”:
im=Image.open(os.path.join(path,infle))
imgs.append(im)
最小宽度=最小宽度时的im.size[0]
创建输出图像时,需要指定需要alpha通道
out_image=Image.new("RGBA", (out_width, out_height))
关于浪费的空间,我想到了两件事:
这有关系吗?如果您只关心文件大小(而不是图像大小),请检查图像的文件大小是否实际增加。因为PNG是一种压缩格式,所以它可能无关紧要
加载后按高度对图像进行排序,将其分组为类似高度的图像,并更改每个组的网格大小。但是,如果使用图像的应用程序必须猜测每个图标的大小,这可能不起作用
out_image=Image.new("RGBA", (out_width, out_height))