简体   繁体   English

使用PIL / PILLOW在图像上写

[英]Write on image using PIL/PILLOW

Good night. 晚安。

Today I`m trying to learn PIL/Pillow in Python. 今天,我正在尝试使用Python学习PIL /枕头。

I used the following code: 我使用以下代码:

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

I don`t know the "draw.text()" function works but i tried to writte the following on a black background image i have. 我不知道“ draw.text()”函数是否有效,但是我尝试在黑色背景图像上写以下内容。

Line 1
Line 2
Line 3
Line 4
Line 5

All i get is these lines one over the other on the same line. 我所得到的只是这些行在同一行上彼此重叠。

How does this function work and how do i get the position of lines in different place instead of one over the other. 此功能如何工作以及如何在不同位置而不是一个位置获得线的位置。

You're resetting x=0 , y=0 each time through the loop: that's why it's overprinting itself. 您每次在循环中都要重置x=0y=0 :这就是为什么它自己套印的原因。 Other than that, you have the right idea. 除此之外,您有正确的想法。

Move those lines outside your loop so they only get set once at the beginning. 将这些行移到循环外,这样它们仅在开始时设置一次。

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

Extensions to pbuck's answer , that moves the initialization of x and y outside of the loop. 扩展了pbuck的answer ,将xy的初始化移出了循环。

  • It is not efficient to save the image in the loop body. 将图像保存在循环主体中效率不高。 This should be moved after the loop. 循环后应将其移动。

  • The font path should use the raw string format to prevent the special meaning of the backslash. 字体路径应使用原始字符串格式,以防止反斜杠的特殊含义。 Alternatively, the backslash can be doubled, or the forward slash can be used. 或者,可以将反斜杠加倍,也可以使用正斜杠。

  • Terminal fonts are usually mono-spaced, which Verdana is not. 终端字体通常是等距的,而Verdana则不是。 The example below uses the font Consolas . 下面的示例使用字体Consolas

  • The font size is 80, thus the vertical increment should be larger than 10 to prevent overprinting. 字体大小为80,因此垂直增量应大于10,以防止叠印。

Example file: 示例文件:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM