我可以问用户一个号码,然后将对应号码的图像粘贴到空白图像中吗?

时间:2019-05-02 12:37:14

标签: python python-imaging-library

我想为图像分配字母或数字,例如字母:“ A”是带有A的图像,数字“ 0”是带有0的图像,依此类推。 我想输入一个数字,例如0,而python会将这个数字链接到正确的图像(带有0的图像)并将该图像粘贴到空白图像。

我已经知道如何将图像与其他图像合并(或合并),我使用枕头:

from PIL import Image

background_img = Image.open("blanc.png")   # the blanc image
IM0 = Image.open("0.jpg")   # The image with a 0
area2 = (0, 208)  # Where the 0 will go on the blanc image
background_img.paste(IM0, area2)   # Paste the 0
background_img.save("Final.png")   # Save the final image

我知道如何用输入来提问

number = input("what number do you want ?")

但是我不知道如何将输入中要写入的数字分配(或链接)到特定图像。

有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

从代码的外观来看,缺少的只是图像的名称。例如,如果用户输入值“ 1”,则需要查找名称为“ 1.jpg”的图像。

如果这是正确的,则可以通过以下操作轻松完成:

file_name_fmt = "{v}.jpg"
val = input()
file_name = file_name_fmt.format(v=val)
if file_name in list_of_images:
    img = Image.open(file_name)

编辑

from PIL import Image

file_name_fmt = "{v}.jpg"

area2 = (0, 208)  # Where the 0 will go on the blanc image
background_img = Image.open("blanc.png")   # the blanc image

val = input("Enter a character for an image representation: ")
file_name = file_name_fmt.format(v=val)
if file_name in list_of_images:
    img = Image.open(file_name)
else:
    raise FileNotFoundError("The file specified doesn't exist")

background_img.paste(img, area2)   # Paste the 0
background_img.save("Final.png")   # Save the final image