Python PIL将文本保存在单独的图像中

时间:2017-04-24 16:10:38

标签: python python-imaging-library

美好的一天。

我正在尝试创建一个for循环来读取文件的行直到满足条件,因此它可以在图像中写入这些行,并且我计划对文件的每一行执行此操作,如下例所示:

Number: 123456789
Connecting to Database

no rows selected

Disconnecting from Database

Number: 9876543211
Connecting to Database

1111;48446511911986;Helen;Thursday
2222;48498489489489;Helen;Friday
3333;84545221185986;Helen;Monday

Disconnecting from Database

Number: 963852741
Connecting to Database

1234;123456789456123;Clyde;Friday
4321;123456789456123;Clyde;Thuesday
1423;123456789456123;Clyde;Sunday
2341;123456789456123;Clyde;Friday

Disconnecting from Database

Number: 456987321
Connecting to Database

no rows selected

Disconnecting from Database

正如您所看到的,每次数据库数据库第二次出现时,下一行是关于新的数字信息,所以我尝试使用数据库这个词作为下面循环的参数。

import os
import PIL
import PIL.Image as Image
import PIL.ImageDraw as ImageDraw
import PIL.ImageFont as ImageFont


img = Image.open("C:/Users/dir/image/black_background.png")
draw = ImageDraw.Draw(img)

fonts_dir = os.path.join(os.environ['WINDIR'], 'Fonts')
font_name = 'consolab.ttf'
font = ImageFont.truetype(os.path.join(fonts_dir, font_name), 15)
x = 2
y = 0
next_print_count = 0
filename = "info.txt"
Number = ""

for line in open(filename):

    if 'Number:' in line:
        Number= line.split(" ",1)[1].strip()

    if 'Testing ' in line:
        line = ""

    draw.text((x, y),line,(200,200,200),font=font)

    y += 15
    img.save(Number + ".png")

问题是,每次启动新文件时,它也会打印前一行的信息。我该如何避免这种情况?

我也尝试使用NUMBER作为参数,但它没有用。

1 个答案:

答案 0 :(得分:1)

you need to delete the current img and draw object every time line is "Disconnecting from Database" and make new objects after deleting them. In your original code, you were also saving the image every line, which is not good either. See the code below.

import os
import PIL
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), 15)
x = 2
y = 0
next_print_count = 0
filename = r'info.txt'
Number = ""

with open(filename) as f: 
    img = Image.open("C:\Users\Public\Pictures\Sample Pictures/Chrysanthemum.jpg")
    draw = ImageDraw.Draw(img)

    for line in f:
        if 'Number:' in line:
            Number= line.split(" ",1)[1].strip()

        if 'Testing ' in line:
            line = ""

        draw.text((x, y),line,(200,200,200),font=font)
        y += 15

        if 'Disconnecting from Database' in line:
            img.save(Number + ".png")
            del draw, img
            img = Image.open("C:\Users\Public\Pictures\Sample Pictures/Chrysanthemum.jpg")
            draw = ImageDraw.Draw(img)
            y=0

results in (only showing two samples images here, but 4 are created)

enter image description here enter image description here