Created
October 3, 2023 01:04
-
-
Save ikapper/9bcf16d01987e7e345d11ceeebbff051 to your computer and use it in GitHub Desktop.
指定してディレクトリに存在するpngをglobで取得し、圧縮レベルを大きめにして別ファイルとして保存しなおす
This file contains 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
import argparse | |
import os | |
import glob | |
# pillow | |
from PIL import Image | |
DEST_DIR_NAME = "reshrinked" | |
def shrink_image(fp: str, to_path: str): | |
""" ファイルサイズが小さくなるように圧縮レベルを大きめにして保存する。 | |
1つのファイルのみを対象とする。 | |
pngファイルが主眼。 | |
""" | |
im = Image.open(fp) | |
im.save(to_path, format="png", compress_level=7) | |
print(f"from: {fp} to: {to_path}") | |
if __name__ == "__main__": | |
# argument parserの定義。ディレクトリの文字列を受け取りたい | |
parser = argparse.ArgumentParser("reshrink png files", description=f""" | |
ディレクトリを指定し、その中にあるpngファイルの圧縮レベルを大きめにしてある子ディレクトリ`{DEST_DIR_NAME}`の中に再配置する。 | |
深さは問わない。 | |
""") | |
parser.add_argument("target", help="対象ディレクトリ") | |
# argument parserから引数の取得。 | |
args = parser.parse_args() | |
apath = args.target | |
# 引数がディレクトリか否か判定し、その中の子ディレクトリを取得し、最終的な引数のリストを作成する | |
if os.path.exists(apath) and os.path.isdir(apath): | |
pass | |
else: | |
raise RuntimeError("ディレクトリを指定してください") | |
dest_dir = os.path.join(apath, DEST_DIR_NAME) | |
if not os.path.exists(dest_dir) or not os.path.isdir(dest_dir): | |
os.mkdir(dest_dir) | |
# forでそれぞれのディレクトリに対してpngを取り出すglobを行う。 | |
for i in glob.iglob(f"{apath}/**/*.png", recursive=True): | |
# それぞれのファイルにshrinkを行う。保存先は、引数のディレクトリに新しいディレクトリを作成し、 | |
afilename = os.path.basename(i) | |
# そこに、同名の子ディレクトリを作成して、そこへ保存する。 | |
# 中間ディレクトリ作成用変数 | |
relative_dir = os.path.dirname(i).replace(apath, "", 1)[1:] # 先頭の/を排除 | |
dest_root_dir = os.path.join(apath, DEST_DIR_NAME, relative_dir) | |
os.makedirs(dest_root_dir, exist_ok=True) | |
shrink_image(i, os.path.join(dest_root_dir, afilename)) | |
print("done") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment