[英]Write on image using PIL/PILLOW
晚安。
今天,我正在尝试使用Python学习PIL /枕头。
我使用以下代码:
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
我所得到的只是这些行在同一行上彼此重叠。
此功能如何工作以及如何在不同位置而不是一个位置获得线的位置。
您每次在循环中都要重置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
扩展了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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.