用pillow给动图加文字,很方便,开心,有兴趣直接看https://github.com/python-pillow/Pillow/issues/3128
我是直接使用网络图片生成的,想使用本地的就把网络的注释掉,直接打开本地图片,会生成一个out.gif文件
很nice,上代码
from PIL import Image, ImageDraw, ImageSequence
import io
from urllib.request import urlopen
import time
start=time.time()
# im = Image.open('C:/Users/Administrator/Desktop/a.gif')#本地图片,如果想做本地的就直接打开本地图片,用网络图片的就用下边的
url="https://xytravel.oss-cn-qingdao.aliyuncs.com/uploads/expression/429/20180809181123673.gif"#网络图片
image_bytes = urlopen(url).read()
# internal data file
data_stream = io.BytesIO(image_bytes)
# open as a PIL image object
im = Image.open(data_stream)
#这里正式开始
frames = []
# Loop over each frame in the animated image
for frame in ImageSequence.Iterator(im):
# Draw the text on the frame
d = ImageDraw.Draw(frame)
d.text((10, 100), "Hello World")
del d
# However, 'frame' is still the animated image with many frames
# It has simply been seeked to a later frame
# For our list of frames, we only want the current frame
# Saving the image without 'save_all' will turn it into a single frame image, and we can then re-open it
# To be efficient, we will save it to a stream, rather than to file
b = io.BytesIO()
frame.save(b, format="GIF")
frame = Image.open(b)
# Then append the single frame image to a list of frames
frames.append(frame)
# Save the frames as a new image
frames[0].save('out.gif', save_all=True, append_images=frames[1:])
end=time.time()
print(end-start)