img resize & crop

Python

from pathlib import Path

from PIL import Image

box_size = 320

input_folder = Path(‘input’)

output_folder = Path(‘output’)

output_folder.mkdir(exist_ok=True)

#画像のリサイズ

for f in input_folder.glob(‘*.jpg’):

img = Image.open(f)

width, height = img.size

ratio = box_size / min(img.size)

resized_img = img.resize((int(width * ratio), int(height * ratio)))

#画像の切り抜き

if width > height:

strip_size = resized_img.size[0] – box.size

cropped_img = resized_img.crop((

strip_size / 2,

0,

resized_img.size[0] – strip_size / 2,

resized_img.size[1]

))

else:

strip_size = resized_img.size[1] – box_size

cropped_img = resized_img.crop((

0,

strip_size / 2,

resized_img.size[0],

resized_img.size[1] – strip_size / 2,

))

#画像をファイルに保存

save_path = output_folder.joinpath(f.name)

cropped_img.save(save_path)

img.close()

引用:https://miyashinblog.com/pictureprocess/

BACK