python 中的叠加图像代码需要一些 for 循环

Overlay images code need some for loop in python

我正在使用以下冗长的代码,是否可以使用一些 for 循环使代码简洁明了。

from PIL import Image
#1
bg = Image.open("bg1.png")
w = Image.open("w1.png")
bg.paste(w, (0,0), w)
#2
body = bg
body1 = Image.open("body.png")
body.paste(body1, (0,0), body1)
#3
eye = bg
eye1 = Image.open("eye1.png")
eye.paste(eye1, (0,0), eye1)
#4
eb = eye
eb1 = Image.open("eb1.png")
eb.paste(eb1, (0,0), eb1)
#5
mouth = eb
mouth1 = Image.open("mouth1.png")
mouth.paste(mouth1, (0,0), mouth1)
#6
nose = mouth
nose1 = Image.open("nose1.png")
nose.paste(nose1, (0,0), nose1)
#7
hair = nose
hair1 = Image.open("h1.png")
hair.paste(hair1, (0,0), hair1)
#8
dress = hair
dress1 = Image.open("d2.png")
dress.paste(dress1, (0,0), dress1)


dress.show()

作为新手 python 的新手

先谢谢你。

我会定义一个函数来将一张图片粘贴到另一张图片上:

def layer_image(image, file_to_paste):
    to_paste = Image.open(file_to_paste)
    return image.paste(to_paste, (0,0), to_paste)

然后您可以遍历图像列表:

files = ["bg1.png", "w1.png", "body.png", "eye1.png", "mouth1.png", "nose1.png", "h1.png", "d2.png"]

start_image = files.pop(0)
img = Image.open(start_image)

for file in files:
    img = layer_image(img, file)