2014-12-05 56 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