Skip to main content

images/reborder.py

1#!/usr/bin/env python3
2"""
3Adds a white border of consistent width around an image.
5I use it when I've taken a screenshot of something on a white background,
6and I want to tidy up the crop quickly.
7"""
9import argparse
10import os
12from PIL import Image, ImageChops, ImageOps
15def parse_args():
16 parser = argparse.ArgumentParser()
18 parser.add_argument("PATH")
19 parser.add_argument("BORDER_WIDTH", type=int)
20 parser.add_argument("--in-place", action="store_true")
22 return parser.parse_args()
25if __name__ == "__main__":
26 args = parse_args()
28 im = Image.open(args.PATH)
30 bg = Image.new(im.mode, im.size, (255, 255, 255))
32 diff = ImageChops.difference(im, bg)
33 diff = ImageChops.add(diff, diff, 2.0, -100)
34 bbox = diff.getbbox()
35 if bbox:
36 im = im.crop(bbox)
38 im = ImageOps.expand(im, border=args.BORDER_WIDTH, fill="white")
40 name, ext = os.path.splitext(args.PATH)
42 if args.in_place:
43 out_path = args.PATH
44 else:
45 out_path = f"{name}.reborder_{args.BORDER_WIDTH}{ext}"
47 im.save(out_path)
49 print(out_path)