""" 给动态的gif图片加文字水印。 本人用这个图片一下了给成千上万的gif图都加上了自己的文字水印。 """ import os from random import choice from PIL import Image,ImageFont,ImageDraw,ImageSequence _colors = ['red','orange','yellow','green','cyan','blue','white'] def watermark_on_gif(in_gif,out_gif,text='scratch8'): """本函数给gif动图加水印""" frames = [] myfont = ImageFont.truetype("msyh.ttf", 12) im = Image.open(in_gif) water_im = Image.new("RGBA", im.size) draw = ImageDraw.Draw(water_im) width,height = water_im.width,water_im.height fontsize = draw.textsize(text,font = myfont) # 文字的宽度和高度 #draw.text(( width//2-fontsize[0]//2, height-fontsize[1]*4), text, font=myfont,fill='gray') draw.text(( 10, 10), text, font=myfont,fill=choice(_colors)) water_mask = water_im.convert("L").point(lambda x: min(x, 160)) water_im.putalpha(water_mask) #print(im.info) index = 0 for frame in ImageSequence.Iterator(im): # 迭代每一帧 frame = frame.convert("RGBA") #frame = Image.alpha_composite(frame,water_im) frame.paste(water_im,None,water_mask) frames.append(frame) newgif = frames[0] newgif.save(out_gif, save_all=True,append_images=frames[1:], quality=85,duration=100) im.close() if __name__ == "__main__": counter = 0 path = os.getcwd() + os.sep + '下载的gif_水印' for file in os.listdir(path): infile = path + os.sep + file outfile = path + os.sep + '__' + file try: watermark_on_gif(infile,outfile) counter += 1 print(infile,'成功加水印') except: pass print('共加水印',counter)
李兴球
李兴球的博客是Python创意编程原创博客