Last active
January 17, 2021 13:43
-
-
Save prs-watch/f62e6e032558b7fd9768559513d7bf40 to your computer and use it in GitHub Desktop.
GIFをマージしてくれるオレオレスクリプト
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| # coding: utf-8 | |
| """ | |
| GIFマージスクリプト | |
| ## 仕様 | |
| - マージしてサイズが大きくなることを回避するため、(9/10)^(n-1)のサイズにする. (マージ量が増えるとどんどん小さいGIFになる) | |
| ## 処理フロー | |
| - アップロードされた順にGIFをバラしてtmpディレクトリにファイルを吐く. | |
| - ファイルを読んで新規のGIFを作る. (ファイル名: GIF-{uuid}.gif) | |
| """ | |
| import glob | |
| import uuid | |
| import os | |
| import shutil | |
| from PIL import Image as pimg | |
| from wand.image import Image as wimg | |
| # 幅の圧縮率 | |
| SIZE_REDUCTION_RATE = 9/10 | |
| def setup(uuid): | |
| """ | |
| 事前準備. | |
| """ | |
| if not os.path.exists(f"tmp/{uuid}"): | |
| os.mkdir(f"tmp/{uuid}") | |
| if not os.path.exists("result"): | |
| os.mkdir("result") | |
| def save_gif_materials(uuid): | |
| """ | |
| GIF素材の生成. | |
| """ | |
| # gif-merge配下に作っておいた資材ディレクトリの指定 | |
| dir_name = input(">> Directory Name of GIFs.") | |
| path = f"gif-merge/{dir_name}" | |
| gifs = glob.glob(f"{path}/*.gif") | |
| gifs.sort() | |
| reduction_rate = SIZE_REDUCTION_RATE ** (len(gifs) - 1) | |
| for gidx, gif in enumerate(gifs): | |
| with wimg(filename=gif) as img: | |
| for iidx in range(len(img.sequence)): | |
| frame = img.sequence[iidx] | |
| i = wimg(image=frame) | |
| i.resize(round(i.size[0] * reduction_rate), round(i.size[1] * reduction_rate)) | |
| i.save(filename=f"tmp/{uuid}/f-{gidx:02}-{iidx:04}.png") | |
| def generate_merged_gif(uuid): | |
| """ | |
| GIFを作成. | |
| """ | |
| # durationの指定 | |
| duration = int(input(">> Duration.")) | |
| materials = glob.glob(f"tmp/{uuid}/*.png") | |
| materials.sort() | |
| pis = [pimg.open(m) for m in materials] | |
| pis[0].save(f"result/GIF-{uuid}.gif", save_all=True, append_images=pis[1:], optimize=False, duration=duration, loop=0) | |
| def clean(uuid): | |
| """ | |
| 事後処理. | |
| """ | |
| shutil.rmtree(f"tmp/{uuid}") | |
| def execute(): | |
| uid = uuid.uuid4() | |
| try: | |
| setup(uid) | |
| save_gif_materials(uid) | |
| generate_merged_gif(uid) | |
| finally: | |
| clean(uid) | |
| if __name__ == "__main__": | |
| execute() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment