2014-12-05 42 views
0

最近,我一直在尝试通过一种简单的方法学习Python(我发现它更有趣,虽然效率不高)。在Python中执行图片编辑

在这个特定的代码,我试图让一个程序来批量生成证书。 我一直在努力解决这个问题,但代码不断覆盖旧的图片并重新保存,而不是从基本变量中获取干净的图片。

我试着将base = Image.open("generico/Certificado.png")移动到criacao(nome)函数中,但后来我被告知“base”没有被定义。

draw = ImageDraw.Draw(base) 
NameError: name 'base' is not defined 

帮助将不胜感激!

import zlib, datetime 
from PIL import Image, ImageFont, ImageDraw 


curso = input("Course: ") 
inicio = input("Date of start (DD/MM): ") 
fim = input("Date ended (formato DD/MM/AAAA): ") 
horas = input ("Total hours spent: ") 
professor = input("Professor: ") 
quantos = int(input("Number of students: ")) 
contador = int(0) 


base = Image.open("generico/Certificado.png") 
font = ImageFont.truetype("arial.ttf", 50) 
draw = ImageDraw.Draw(base) 


def criacao(nome): 
    nome_arquivo = str(datetime.date.today()) + " " + nome[0].upper() + nome[1:len(nome)].lower() + " " + curso 
    draw.text((750,1065), nome.upper(), font=font, fill=(0,0,0,0)) 
    draw.text((750,1414), curso.upper(), font=font, fill=(0,0,0,0)) 
    draw.text((1220,1625), inicio, font=font, fill=(0,0,0,0)) 
    draw.text((1500,1625), fim, font=font, fill=(0,0,0,0)) 
    draw.text((1540,1750), horas + ".", font=font, fill=(0,0,0,0)) 
    draw.text((1740,2130), str(datetime.date.today()), font=font, fill=(0,0,0,0)) 
    draw.text((1550,2680), professor, font=font, fill=(0,0,0,0)) 
    base.save("Criado/" + nome_arquivo + ".png") 


while contador < quantos: 
    criacao(input("Student's name: ")) 
    contador += 1 

回答

1

我怀疑你需要除了移动draw = ImageDraw.Draw(base)行定义base行。您当前的错误与该行无法看到base有关,它似乎是您操纵图像数据的手段,因此它很有意义。

试试这个:

font = ImageFont.truetype("arial.ttf", 50) 

def criacao(nome): 
    base = Image.open("generico/Certificado.png")  # move this line from above 
    draw = ImageDraw.Draw(base)      # this one too 

    nome_arquivo = str(datetime.date.today()) + " " + nome[0].upper() + nome[1:len(nome)].lower() + " " + curso 
    draw.text((750,1065), nome.upper(), font=font, fill=(0,0,0,0)) 
    draw.text((750,1414), curso.upper(), font=font, fill=(0,0,0,0)) 
    draw.text((1220,1625), inicio, font=font, fill=(0,0,0,0)) 
    draw.text((1500,1625), fim, font=font, fill=(0,0,0,0)) 
    draw.text((1540,1750), horas + ".", font=font, fill=(0,0,0,0)) 
    draw.text((1740,2130), str(datetime.date.today()), font=font, fill=(0,0,0,0)) 
    draw.text((1550,2680), professor, font=font, fill=(0,0,0,0)) 
    base.save("Criado/" + nome_arquivo + ".png") 
+0

谢谢了很多! – 2014-12-05 16:41:36