Skip to content

Instantly share code, notes, and snippets.

@kotoripiyopiyo
Created April 26, 2021 12:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kotoripiyopiyo/c0101bb649f810f26aeea943a5da7157 to your computer and use it in GitHub Desktop.
Save kotoripiyopiyo/c0101bb649f810f26aeea943a5da7157 to your computer and use it in GitHub Desktop.
リサイズ、ロゴ追加、保存。フォルダの中から画像ファイルだけを抜き出し。拡張子はjpg png gif bmp jpegでそれぞれ大文字小文字対応
#!/usr/bin/env python3
# 画像をリサイズしてロゴを貼り付ける
import os
from PIL import Image
import re
dirname = './chapter17/'
os.makedirs('changed', exist_ok=True)
new_dirname = './changed'
LOGO_FILENAME = 'catlogo.png'
# ロゴを取得
logo_img = Image.open(os.path.join(dirname, LOGO_FILENAME))
logo_width, logo_height = logo_img.size
# リサイズとロゴ追加の関数
def convert_img(base_img, new_width):
# 縦横比の維持
width, height = base_img.size
new_height = round(height * new_width / width)
# リサイズ
resized_img = base_img.resize((new_width, new_height))
# ロゴの追加
resized_img_width, resized_img_height = resized_img.size
resized_img.paste(logo_img, (resized_img_width - logo_width, resized_img_height - logo_height), logo_img)
# png保存するためにコンバート
return resized_img.convert('RGBA')
# マッチするファイルの正規表現を作る
img_regex = re.compile(r'\.jpg$|\.gif$|\.png$|\.bmp$|\.jpeg$', re.I)
# todo ファイルを取得して変形
file_list = os.listdir(dirname) # ファイル名一覧を取得
new_img_width = 400 #リサイズしたい大きさ
i = 0 # ファイル名用
for img in file_list:
mo = img_regex.search(img)
if mo == None:
print(img + ' は画像じゃありません')
continue
elif img == LOGO_FILENAME:
print('これはロゴです')
continue
else:
orizinal_img = Image.open(dirname + img)
i += 1
print(f'{i:02}番目「{img}」の画像をリサイズ、ロゴ追加、保存')
converted_img = convert_img(orizinal_img, new_img_width)
# 保存
filename = f'{i:02}'
converted_img.save(os.path.join(new_dirname, filename+'.png'))
@kotoripiyopiyo
Copy link
Author

defを無理やり使ったのがポイント

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment