晚安。
今天我正在尝试用Python学习PIL / Pillow。
我使用了以下代码:
import PIL
import PIL.Image as Image
import PIL.ImageDraw as ImageDraw
import PIL.ImageFont as ImageFont
font = ImageFont.truetype("C:\Windows\Fonts\Verdanab.ttf", 80)
img = Image.open("C:/Users/imagem/fundo_preto.png")
draw = ImageDraw.Draw(img)
filename = "info.txt"
for line in open(filename):
print line
x = 0
y = 0
draw.text((x, y),line,(255,255,255),font=font)
img.save("a_test.png")
x += 10
y += 10
我不知道“draw.text()”函数有效但我试图在我拥有的黑色背景图像上写下以下内容。
Line 1
Line 2
Line 3
Line 4
Line 5
我得到的就是这些线在同一条线上一个接一个。
这个功能是如何工作的,我如何在不同的位置获得线的位置而不是一个在另一个位置。
答案 0 :(得分:2)
每次循环都会重置x=0
,y=0
:这就是为什么它会叠印自己。除此之外,你有正确的想法。
将这些线移到循环之外,这样它们只能在开头设置一次。
x = 0
y = 0
for line in open(filename):
print line
draw.text((x, y),line,(255,255,255),font=font)
img.save("a_test.png")
x += 10
y += 10
答案 1 :(得分:1)
对pbuck answer的扩展,将x
和y
的初始化移到了循环之外。
将图像保存在循环体中效率不高。这应该在循环之后移动。
字体路径应使用原始字符串格式来防止反斜杠的特殊含义。或者,反斜杠可以加倍,或者可以使用正斜杠。
终端字体通常是单行间距,而Verdana
则不是。以下示例使用字体Consolas
。
字体大小为80,因此垂直增量应大于10,以防止叠印。
示例文件:
import os
import PIL.Image as Image
import PIL.ImageDraw as ImageDraw
import PIL.ImageFont as ImageFont
fonts_dir = os.path.join(os.environ['WINDIR'], 'Fonts')
font_name = 'consolab.ttf'
font = ImageFont.truetype(os.path.join(fonts_dir, font_name), 80)
img = Image.new("RGB", (400, 350), "black")
draw = ImageDraw.Draw(img)
filename = "info.txt"
x = y = 0
for line in open(filename):
print(line)
draw.text((x, y), line, (255, 255, 255), font=font)
x += 20
y += 80
img.save("a_test.png")