# GIF处理import osfrom itertools import productfrom PIL import Imagefrom PIL import ImageDraw, ImageFontimport utilsimport imageioimport copydef process_gif_watermark(gif_dir, new_dir): # print(os.getcwd()) baseDir = os.getcwd() gifDir = baseDir + "/" + gif_dir gifFiles = os.listdir(gif_dir) # print(gif_dir) for file in gifFiles: gifFile = gifDir + "/" + file print(gifFile, utils.isImg(gifFile)) if not utils.isImg(gifFile): continue frames, framesSmall = gifSplit(gifFile) gifCreate(frames, new_dir + "/" + file) gifCreate(framesSmall, new_dir + "/" + "small_"+file)def processImgWatermarkSmall(img_array): width, height = img_array.size rgbSmall = img_array rgbSmall.thumbnail((width / 2, height / 2), reducing_gap=1.0) return rgbSmalldef processImgWatermark(img_array): """ :param img_array: :return: :description: 600x600(原始),300x300 """ rgb = img_array.convert("RGB") width, height = img_array.size # img_array.show() for pos in product(range(width), range(height)): if sum(rgb.getpixel(pos)[:3]) > 720: rgb.putpixel(pos, (255, 255, 255)) draw = ImageDraw.Draw(rgb) font = ImageFont.truetype(font="fonts/PingFang Medium_downcc.otf", size=60) draw.text((5, height - 100), "LZC", (246, 246, 246), font=font) draw.text((width - 120, height - 100), "LZC", (246, 246, 246), font=font) return rgbdef gifSplit(src_path): """ 将一张GIF动图分解到指定文件夹 src_path:要分解的gif的路径 dest_path:保存后的gif路径 """ img = Image.open(src_path) frames = [] framesSmall = [] lf = img.n_frames for i in range(img.n_frames): if i <= 0 or i == lf - 1: continue img.seek(i) # new = Image.new("RGBA", img.size) nimg = processImgWatermark(img) # nimgCp = copy.deepcopy(nimg) nimgSmall = processImgWatermarkSmall(nimg) frames.append(nimg) framesSmall.append(nimgSmall) # # new.paste(nimg) # new.save(os.path.join(dest_path, "%d.%s" % (i, suffix))) return frames, framesSmalldef gifCreate(frames, gif_name, duration=0.1): """ :param frames: 这个列表用于存放生成动图的图片 :param gif_name: 字符串,所生成gif文件名,带.gif后缀 :param duration: 图像间隔时间 :return: """ imageio.mimsave(gif_name, frames, 'GIF', duration=duration) return整体处理并不理想,原始图片80KB,大图gif 1.3M,小图gif 801KB。
回头试试另一种方案:frame保存为jpg,降低quality到60,再合并jpg文件生成gif,最后移除jpg文件
2022-08-10实验后记录:
保存jpg再合并的方案不合理,jpg单个文件10kb左右,85个文件合并后是2.7M。
庆幸有pygifsicle
第一种方案生成gif是1.3M,压缩后70kb
pip install pygifsicle使用:
from pygifsicle import optimizeoptimize(destFile, colors=32)#新文件,color视情况而定optimize(destFile, "newFilePath", colors=32) | 留言与评论(共有 0 条评论) “” |