简体   繁体   中英

Moving text lower one image at a time in a loop, using PIL

I am new to PIL. I am attempting to save multiple images in a loop in order to change the position of the text in each image.

Here is my code:

from PIL import Image, ImageDraw, ImageFont
import os

files = []
C = 0
base = Image.open('car.jpg').convert('RGBA')

txt = Image.new('RGBA', base.size, (255,255,255,0))

fnt = ImageFont.truetype('calibrib.ttf', 40)
d = ImageDraw.Draw(txt)

W = 0
while C < 175:
    d.text((0,W), "Test Text", font=fnt, fill=(255,255,255,255))
    out = Image.alpha_composite(base, txt)

    f = (3-len(str(C)))*'0'+str(C)
    folder = os.getcwd()
    out.save(folder + '/images/a%s.png' % f, "PNG")
    files.append('a%s.png' % f)

    W = W+1
    C =  C+1

This is how the first output image looks like: 在此处输入图片说明

My desired output is to see "Test Text" centered vertically in the last image.

The text should move lower and lower one image at a time in the loop.

But, instead I get this: 在此处输入图片说明

the ImageDraw.Draw call makes txt an image to be drawn on in place, each time you call d.text you are drawing new text on the txt image without removing the previous text from the last iterations. To fix this you need to reset the txt object on each iteration. You can do this by calling

txt = Image.new('RGBA', base.size, (255,255,255,0))
d = ImageDraw.Draw(txt)

inside the while loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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