cmd/crop.py
Ethan Dalool 4a9051e617
Big migrations and linting.
With pathclass.glob_many, we can clean up and feel more confident
about many programs that use pipeable to take glob patterns.

Added return 0 to all programs that didn't have it, so we have
consistent and explicit command line return values.

Other linting and whitespace.
2021-09-23 23:42:45 -07:00

56 lines
1.7 KiB
Python

import argparse
import PIL.Image
import sys
from voussoirkit import pathclass
from voussoirkit import pipeable
def crop(file, crops, *, inplace=False):
image = PIL.Image.open(file.absolute_path)
if len(crops) == 2:
crops.extend(image.size)
if crops[0] < 0: crops[0] = image.size[0] + crops[0]
if crops[1] < 0: crops[1] = image.size[1] + crops[1]
if crops[2] < 0: crops[2] = image.size[0] + crops[2]
if crops[3] < 0: crops[3] = image.size[1] + crops[3]
if crops[2] == 0: crops[2] = image.size[0]
if crops[3] == 0: crops[3] = image.size[1]
image = image.crop(crops)
if inplace:
newname = file
else:
suffix = '_'.join(str(x) for x in crops)
suffix = f'_{suffix}'
base = file.replace_extension('').basename
newname = file.parent.with_child(base + suffix).add_extension(file.extension)
pipeable.stdout(newname.absolute_path)
image.save(newname.absolute_path, exif=image.info.get('exif', b''), quality=100)
def crop_argparse(args):
patterns = pipeable.input(args.pattern, skip_blank=True, strip=True)
files = pathclass.glob_many(patterns, files=True)
for file in files:
crop(
file,
crops=args.crops,
inplace=args.inplace,
)
return 0
def main(argv):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('pattern')
parser.add_argument('crops', nargs='+', type=int, default=None)
parser.add_argument('--inplace', action='store_true')
parser.set_defaults(func=crop_argparse)
args = parser.parse_args(argv)
return args.func(args)
if __name__ == '__main__':
raise SystemExit(main(sys.argv[1:]))