2020-07-08 05:10:21 +00:00
|
|
|
import argparse
|
2021-06-04 20:13:11 +00:00
|
|
|
import PIL.Image
|
2020-07-08 05:10:21 +00:00
|
|
|
import sys
|
|
|
|
|
2021-09-24 06:42:34 +00:00
|
|
|
from voussoirkit import pathclass
|
2021-06-04 03:43:27 +00:00
|
|
|
from voussoirkit import pipeable
|
2020-07-08 05:10:21 +00:00
|
|
|
|
2021-09-24 06:42:34 +00:00
|
|
|
def crop(file, crops, *, inplace=False):
|
|
|
|
image = PIL.Image.open(file.absolute_path)
|
2020-07-08 05:10:21 +00:00
|
|
|
if len(crops) == 2:
|
2021-06-04 03:43:27 +00:00
|
|
|
crops.extend(image.size)
|
2020-09-23 19:47:44 +00:00
|
|
|
|
2021-06-04 03:43:27 +00:00
|
|
|
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]
|
2020-09-23 19:47:44 +00:00
|
|
|
|
2021-06-04 03:43:27 +00:00
|
|
|
image = image.crop(crops)
|
2020-07-08 05:10:21 +00:00
|
|
|
if inplace:
|
2021-09-24 06:42:34 +00:00
|
|
|
newname = file
|
2020-07-08 05:10:21 +00:00
|
|
|
else:
|
|
|
|
suffix = '_'.join(str(x) for x in crops)
|
|
|
|
suffix = f'_{suffix}'
|
2021-09-24 06:42:34 +00:00
|
|
|
base = file.replace_extension('').basename
|
|
|
|
newname = file.parent.with_child(base + suffix).add_extension(file.extension)
|
2020-07-08 05:10:21 +00:00
|
|
|
|
2021-09-24 06:42:34 +00:00
|
|
|
pipeable.stdout(newname.absolute_path)
|
|
|
|
image.save(newname.absolute_path, exif=image.info.get('exif', b''), quality=100)
|
2020-07-08 05:10:21 +00:00
|
|
|
|
|
|
|
def crop_argparse(args):
|
2021-09-24 06:42:34 +00:00
|
|
|
patterns = pipeable.input(args.pattern, skip_blank=True, strip=True)
|
|
|
|
files = pathclass.glob_many(patterns, files=True)
|
|
|
|
|
|
|
|
for file in files:
|
2020-07-08 05:10:21 +00:00
|
|
|
crop(
|
2021-09-24 06:42:34 +00:00
|
|
|
file,
|
2020-07-08 05:10:21 +00:00
|
|
|
crops=args.crops,
|
|
|
|
inplace=args.inplace,
|
|
|
|
)
|
2021-09-24 06:42:34 +00:00
|
|
|
return 0
|
2020-07-08 05:10:21 +00:00
|
|
|
|
|
|
|
def main(argv):
|
|
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
|
|
|
|
|
|
parser.add_argument('pattern')
|
|
|
|
parser.add_argument('crops', nargs='+', type=int, default=None)
|
2021-02-21 05:01:55 +00:00
|
|
|
parser.add_argument('--inplace', action='store_true')
|
2020-07-08 05:10:21 +00:00
|
|
|
parser.set_defaults(func=crop_argparse)
|
|
|
|
|
|
|
|
args = parser.parse_args(argv)
|
|
|
|
return args.func(args)
|
2019-06-12 05:41:31 +00:00
|
|
|
|
2020-07-08 05:10:21 +00:00
|
|
|
if __name__ == '__main__':
|
|
|
|
raise SystemExit(main(sys.argv[1:]))
|