pythonpython-imaging-library

Write on image using PIL/PILLOW


Good night.

Today I`m trying to learn PIL/Pillow in Python.

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.

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.


Solution

  • You're resetting x=0, y=0 each time through the loop: that's why it's overprinting itself. 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