简体   繁体   English

使用PIL一次将文本移动到一个循环中降低一幅图像的位置

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

I am new to PIL. 我是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. ImageDraw.Draw调用使txt成为要在其上绘制的图像,每次调用d.text时,您都将在txt图像上绘制新文本,而不会从上次迭代中删除先前的文本。 To fix this you need to reset the txt object on each iteration. 要解决此问题,您需要在每次迭代时重置txt对象。 You can do this by calling 您可以通过致电

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

inside the while loop. 在while循环中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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