|
3 | 3 | Image Thumbnail |
4 | 4 | =============== |
5 | 5 |
|
6 | | -You can use matplotlib to generate thumbnails from existing images. |
| 6 | +You can use Matplotlib to generate thumbnails from existing images. |
7 | 7 | Matplotlib relies on Pillow_ for reading images, and thus supports all formats |
8 | 8 | supported by Pillow. |
9 | 9 |
|
10 | 10 | .. _Pillow: http://python-pillow.org/ |
11 | 11 | """ |
12 | 12 |
|
13 | | -# build thumbnails of all images in a directory |
| 13 | +from argparse import ArgumentParser |
| 14 | +from pathlib import Path |
14 | 15 | import sys |
15 | | -import os |
16 | | -import glob |
17 | 16 | import matplotlib.image as image |
18 | 17 |
|
19 | 18 |
|
20 | | -if len(sys.argv) != 2: |
21 | | - print('Usage: python %s IMAGEDIR' % __file__) |
22 | | - raise SystemExit |
23 | | -indir = sys.argv[1] |
24 | | -if not os.path.isdir(indir): |
25 | | - print('Could not find input directory "%s"' % indir) |
26 | | - raise SystemExit |
| 19 | +parser = ArgumentParser( |
| 20 | + description="Build thumbnails of all images in a directory.") |
| 21 | +parser.add_argument("imagedir", type=Path) |
| 22 | +args = parser.parse_args() |
| 23 | +if not args.imagedir.isdir(): |
| 24 | + sys.exit(f"Could not find input directory {args.imagedir}") |
27 | 25 |
|
28 | | -outdir = 'thumbs' |
29 | | -if not os.path.exists(outdir): |
30 | | - os.makedirs(outdir) |
| 26 | +outdir = Path("thumbs") |
| 27 | +outdir.mkdir(parents=True, exist_ok=True) |
31 | 28 |
|
32 | | -for fname in glob.glob(os.path.join(indir, '*.png')): |
33 | | - basedir, basename = os.path.split(fname) |
34 | | - outfile = os.path.join(outdir, basename) |
35 | | - fig = image.thumbnail(fname, outfile, scale=0.15) |
36 | | - print('saved thumbnail of %s to %s' % (fname, outfile)) |
| 29 | +for path in args.imagedir.glob("*.png"): |
| 30 | + outpath = outdir / path.name |
| 31 | + fig = image.thumbnail(path, outpath, scale=0.15) |
| 32 | + print(f"saved thumbnail of {path} to {outpath}") |
0 commit comments