使用 PIL 循环移动文本一次降低一个图像

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

我是 PIL 的新手。我正在尝试循环保存多张图片,以便更改每张图片中文本的位置。

这是我的代码:

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

这是第一个输出图像的样子:

我想要的输出是看到 "Test Text" 在最后一张图片中垂直居中。

文本应在循环中一次一个图像地向下移动。

但是,我得到的是:

ImageDraw.Draw 调用使 txt 成为要在适当位置绘制的图像,每次调用 d.text 时,您都在 txt 图像上绘制新文本,而不会从上次迭代中删除以前的文本.要解决此问题,您需要在每次迭代时重置 txt 对象。您可以通过调用

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

在 while 循环中。