我有以下代码(源自this answer),我尝试添加数字的文本绘图。它不起作用。它不会创建图像,并且cmd提示太快,无法查看它正在抛出的错误。
#!/usr/bin/env python
import os.path
import sys
from time import strftime
import Image
import ImageDraw
import ImageFont
row_size = 3
margin = 3
def generate_montage(filenames, output_fn):
images = [Image.open(filename) for filename in filenames]
width = max(image.size[0] + margin for image in images)*row_size
height = sum(image.size[1] + margin for image in images)
montage = Image.new(mode='RGBA', size=(width, height), color=(0,0,0,255))
image_font = ImageFont.truetype('font/Helvetica.ttf', 18)
draw = ImageDraw.Draw(montage)
max_x = 0
max_y = 0
offset_x = 0
offset_y = 0
for i,image in enumerate(images):
montage.paste(image, (offset_x, offset_y))
text_coords = offset_x + image.size[0] - 45, offset_y + 120
draw.text(text_coords, '#{0}'.format(i+1), font=image_font)
max_x = max(max_x, offset_x + image.size[0])
max_y = max(max_y, offset_y + image.size[1])
if i % row_size == row_size-1:
offset_y = max_y + margin
offset_x = 0
else:
offset_x += margin + image.size[0]
montage = montage.crop((0, 0, max_x, max_y))
montage.save(output_fn)
if __name__ == '__main__':
basename = strftime("Montage %Y-%m-%d at %H.%M.%S.png")
exedir = os.path.dirname(os.path.abspath(sys.argv[0]))
filename = os.path.join(exedir, basename)
generate_montage(sys.argv[1:], filename)
答案 0 :(得分:1)
您可以按 Win + r cmd Enter 打开命令行窗口。进入那里后,执行程序仍然可以看到它的输出。另一个选择是包装generate_montage
调用,如下所示:
try:
generate_montage(sys.argv[1:], filename)
except:
import traceback,time
traceback.print_exc()
time.sleep(600)
在任何情况下,最可能的问题是找不到字体,因为您是从相对于cwd的目录加载它。传入基本目录,如下所示:
base = os.path.dirname(os.path.abspath(__file__))
try:
fn = os.path.join(base, 'font', 'Helvetica.ttf')
image_font = ImageFont.truetype(fn, 18)
except:
try:
fn = os.path.join(base, 'font', 'Helvetica-18.pil')
image_font = ImageFont.load(fn)
except:
image_font = ImageFont.load_default()
TTF字体加载doesn't work的原因可能是因为your PIL has been compiled without TTF support。