【问题标题】:combine multiple png to a single transparent png using PIL使用 PIL 将多个 png 组合成一个透明 png
【发布时间】: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


    【解决方案1】:
    out_image=Image.new("RGB", (out_width, out_height))
    

    您需要在创建输出图像时指定您想要一个 Alpha 通道

    out_image=Image.new("RGBA", (out_width, out_height))
    

    关于浪费的空间,我想到了两件事:

    1. 重要吗?如果您只关心文件大小(而不是图像大小),请检查图像是否实际增加了文件大小。由于 PNG 是一种压缩格式,因此可能无关紧要。

    2. 加载后按高度对图像进行排序,将它们分组为相似高度的图像,并更改每组的网格大小。如果使用图像的应用程序必须猜测每个图标的大小,这可能不起作用。

    【讨论】:

      猜你喜欢
      • 2011-11-08
      • 2023-03-17
      • 1970-01-01
      • 2011-04-24
      • 1970-01-01
      • 2011-06-02
      • 1970-01-01
      相关资源
      最近更新 更多