crop-resize.py
入力画像のトリミング、中央揃え、サイズ変更を行う Python スクリプトを次に示します。
usage: crop-resize.py [-h] [-s N N] [-q] [--outputdir DIR]
files [files ...]
Resize the image to given size. Don't strech images, crop and center
instead.
positional arguments:
files image filenames to process
optional arguments:
-h, --help show this help message and exit
-s N N, --size N N new image size (default: [120, 80])
-q, --quiet
--outputdir DIR directory where to save resized images (default: .)
コア機能は次のとおりです。
def crop_resize(image, size, ratio):
# crop to ratio, center
w, h = image.size
if w > ratio * h: # width is larger then necessary
x, y = (w - ratio * h) // 2, 0
else: # ratio*height >= width (height is larger)
x, y = 0, (h - w / ratio) // 2
image = image.crop((x, y, w - x, h - y))
# resize
if image.size > size: # don't stretch smaller images
image.thumbnail(size, Image.ANTIALIAS)
return image
@choroba さんの bash スクリプトとよく似ています。