Python粘贴多个图像来创建一个

时间:2013-12-10 17:20:35

标签: python python-imaging-library

我正在开发一个应用程序,我需要在用户制作的7个选项中创建一个图像,我有这个工作,但我想知道是否有更好的方法来做到这一点?目前我这样做,

    #!/usr/bin/env

import Image

def main(   ): #{

    layer1 = Image.open("img/layer1.png");
    layer2 = Image.open("img/layer2.png");
    layer3 = Image.open("img/layer3.png");
    layer4 = Image.open("img/layer4.png");
    layer5 = Image.open("img/layer5.png");
    layer6 = Image.open("img/layer6.png");
    layer7 = Image.open("img/layer7.png");

    image  = Image.new( "RGBA", ( 704, 469 ) );

    image.paste(layer1, ( 0, 0) );

    image.save("img/new_image.png");

    base = Image.open("img/new_image.png");

    base.paste(layer2, (0,0), layer2.convert("RGBA") );

    image.save("img/new_image.png");

    base.paste(layer3, (0,0), layer3.convert("RGBA") );

    image.save("img/new_image.png");

    base.paste(layer4, (0,0), layer4.convert("RGBA") );

    image.save("img/new_image.png");

    base.paste(layer5, (0,0), layer5.convert("RGBA") );

    image.save("img/new_image.png");

    base.paste(layer6, (0,0), layer6.convert("RGBA") );

    image.save("img/new_image.png");

    base.paste(layer7, (0,0), layer7.convert("RGBA") );

    image.open("img/new_image.png");

    print image.info;

    del base;
    del image;

#}

if ( __name__ == "__main__" ): #{

    main();

#}

有没有更好的方法来做到这一点,最终我想创建最终图像以将随机字符串作为名称,有没有办法做到这一点,并让脚本返回该名称,以便我可以使用它在哪里?

1 个答案:

答案 0 :(得分:0)

试试这个:

#!/usr/bin/env python
from PIL import Image
import glob
def main():

layers_l = glob.glob("*.png")
layers_l = map(lambda x :Image.open(x) ,layers_l)

image  = Image.new( "RGBA", ( 2048*3, 2048*3 ) )
image.save("new_image.png")
base = Image.open("new_image.png")

for layer in layers_l[1:]:
    base.paste(layer, (0,0), layer.convert("RGBA") )
    image.save("new_image.png")
    print layer

print image.info

if ( __name__ == "__main__" ): main()