【问题标题】:Write on image using PIL/PILLOW使用 PIL/PILLOW 在图像上书写
【发布时间】:2017-04-23 09:21:45
【问题描述】:

晚安。

今天我正在尝试用 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

我得到的只是这些行在同一行上一个接一个。

这个功能是如何工作的,我如何在不同的地方而不是一个在另一个地方获得线条的位置。

【问题讨论】:

  • xy的初始化应该移到循环之前,否则x += 10; y += 10起不到任何作用。我也会在循环后保存图像。字体路径可以作为原始字符串r"C:\Windows\Fonts\Verdana.ttf" 给出,以防止字符串中反斜杠的特殊含义。
  • 既然我们在谈论字体。我是否获得了模拟终端字体的字体?我正在尝试模拟命令提示符终端的屏幕,但我使用的字体不是那么好。
  • 也许,您想使用等距字体。顺便说一句,Windows 字体目录的更便携方式:os.path.join(os.environ['WINDIR'], 'Fonts').

标签: python pillow


【解决方案1】:

每次循环都在重置x=0y=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

【讨论】:

  • 顺便说一句,我正在尝试使用终端窗口字体,但显然 PIL 不支持它。如何使用终端字体?
  • 图像应该保存循环一次。
【解决方案2】:

pbuck 的answer 的扩展,将xy 的初始化移到循环之外。

  • 将图像保存在循环体中效率不高。这应该在循环之后移动。

  • 字体路径应使用原始字符串格式,以防止反斜杠的特殊含义。或者,反斜杠可以加倍,也可以使用正斜杠。

  • 终端字体通常是等距的,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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    • 1970-01-01
    • 1970-01-01
    • 2014-01-27
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多