使用 PIL/PILLOW 在图像上书写
Write on image using PIL/PILLOW
晚安
今天我想在 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
我得到的只是同一行上的这些行。
这个功能是如何工作的,我如何在不同的地方而不是一个在另一个地方获得线的位置。
您每次循环都在重置 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 的扩展,将 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")
晚安
今天我想在 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
我得到的只是同一行上的这些行。
这个功能是如何工作的,我如何在不同的地方而不是一个在另一个地方获得线的位置。
您每次循环都在重置 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 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")