【发布时间】:2017-05-18 06:12:02
【问题描述】:
我正在尝试获取一个.GIF 文件,用PIL 打开它,然后逐帧在其上写入文本。但是,代码只保存了一个图像(1 帧;它不像 .GIF 文件那样移动。
代码:
import giphypop
from urllib import request
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
g = giphypop.Giphy()
img = g.translate("dog")
request.urlretrieve(img.media_url, "test.gif")
opened_gif = Image.open("test.gif")
opened_gif.load()
opened_gif.seek(1)
try:
while 1:
slide = opened_gif.seek(opened_gif.tell()+1)
draw = ImageDraw.Draw(slide)
# font = ImageFont.truetype(<font-file>, <font-size>)
font = ImageFont.truetype("sans-serif.ttf", 16)
# draw.text((x, y),"Sample Text",(r,g,b))
draw.text((0, 0),"Sample Text",(255,255,255),font=font)
except EOFError:
pass # end of sequence
except AttributeError:
print("Couldn't use this slide")
opened_gif.save('test_with_caption.gif')
【问题讨论】:
-
据我所知,PIL 无法保存动画 GIF。您将不得不在分离的图像中写入每一帧,并使用不同的工具将所有帧连接到一个 GIF 中。您可以尝试
ffmpeg或ImageMagic将图像加入动画 GIF。或者您可以查看moviepy 模块来创建动画。 -
@furas 好的。但是,为什么它不保存示例文本的 1 帧呢?它所做的只是保存 1 张带有 no 文本的图像。
-
我无法检查 - 你在
slice上工作,但你保存opened_gif -
顺便说一句:不要在
except中使用pass,因为你可能会遇到一些你不知道的错误。 -
查看如何使用框架:stackoverflow.com/a/35615319/1832058
标签: python image python-3.x python-imaging-library gif