簡體   English   中英

使用PIL / PILLOW在圖像上寫

[英]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=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

擴展了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")

結果

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM