cmd/grayscale.py

48 lines
1.4 KiB
Python
Raw Normal View History

2020-09-20 20:18:30 +00:00
import argparse
2020-06-17 20:43:25 +00:00
import PIL.Image
import sys
from voussoirkit import pathclass
from voussoirkit import pipeable
2020-06-17 20:43:25 +00:00
2020-09-20 20:18:30 +00:00
def grayscale(filename, *, inplace=False):
filename = pathclass.Path(filename)
basename = filename.replace_extension('').basename
if basename.endswith('_gray'):
return
if inplace:
new_filename = filename
else:
basename += '_gray'
new_filename = filename.parent.with_child(basename).add_extension(filename.extension)
image = PIL.Image.open(filename.absolute_path)
image = image.convert('LA').convert(image.mode)
image.save(new_filename.absolute_path, exif=image.info.get('exif', b''))
return new_filename
2020-09-20 20:18:30 +00:00
def grayscale_argparse(args):
patterns = pipeable.input_many(args.patterns, skip_blank=True, strip=True)
files = pathclass.glob_many_files(patterns)
for file in files:
new_filename = grayscale(file, inplace=args.inplace)
if new_filename:
pipeable.stdout(new_filename.absolute_path)
return 0
2020-09-20 20:18:30 +00:00
2020-06-17 20:43:25 +00:00
def main(argv):
2020-09-20 20:18:30 +00:00
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('patterns', nargs='+')
parser.add_argument('--inplace', action='store_true')
2020-09-20 20:18:30 +00:00
parser.set_defaults(func=grayscale_argparse)
args = parser.parse_args(argv)
return args.func(args)
2020-06-17 20:43:25 +00:00
if __name__ == '__main__':
raise SystemExit(main(sys.argv[1:]))