Skip to main content

images/squarify.py

1#!/usr/bin/env python3
2"""
3Creates a square crop of an image.
4"""
6from pathlib import Path
7import sys
9from PIL import Image
12if __name__ == "__main__":
13 try:
14 path = Path(sys.argv[1])
15 except IndexError:
16 sys.exit(f"Usage: {__file__} IMAGE_PATH")
18 im = Image.open(path)
20 out_path = path.with_suffix(".square" + path.suffix)
21 assert out_path != path
23 if im.width == im.height:
24 print(path)
25 elif im.width > im.height:
26 left = (im.width - im.height) / 2
27 upper = 0
28 right = im.width - (im.width - im.height) / 2
29 lower = im.height
31 crop_im = im.crop((left, upper, right, lower))
32 crop_im.save(out_path)
33 print(out_path)
34 elif im.height > im.width:
35 left = 0
36 upper = (im.height - im.width) / 2
37 right = im.width
38 lower = im.height - (im.height - im.width) / 2
40 crop_im = im.crop((left, upper, right, lower))
41 crop_im.save(out_path)
42 print(out_path)
44 # main()