Add --inplace argument to overwrite input file.

This commit is contained in:
voussoir 2020-07-07 22:09:48 -07:00
parent 17afe6a9b9
commit cb84584202

View file

@ -6,9 +6,15 @@ import sys
from voussoirkit import imagetools from voussoirkit import imagetools
from voussoirkit import winglob from voussoirkit import winglob
filenames = sys.argv[1] def resize(
filename,
def resize(filename, new_x=None, new_y=None, scale=None, nearest_neighbor=False): new_x=None,
new_y=None,
*,
inplace=False,
nearest_neighbor=False,
scale=None,
):
i = Image.open(filename) i = Image.open(filename)
(image_width, image_height) = i.size (image_width, image_height) = i.size
@ -18,7 +24,6 @@ def resize(filename, new_x=None, new_y=None, scale=None, nearest_neighbor=False)
elif scale: elif scale:
new_x = int(image_width * scale) new_x = int(image_width * scale)
new_y = int(image_height * scale) new_y = int(image_height * scale)
print(new_x, new_y)
if new_x == 0: if new_x == 0:
(new_x, new_y) = imagetools.fit_into_bounds(image_width, image_height, 10000000, new_y) (new_x, new_y) = imagetools.fit_into_bounds(image_width, image_height, 10000000, new_y)
@ -30,9 +35,13 @@ def resize(filename, new_x=None, new_y=None, scale=None, nearest_neighbor=False)
i = i.resize( (new_x, new_y), Image.NEAREST) i = i.resize( (new_x, new_y), Image.NEAREST)
else: else:
i = i.resize( (new_x, new_y), Image.ANTIALIAS) i = i.resize( (new_x, new_y), Image.ANTIALIAS)
suffix = '_{width}x{height}'.format(width=new_x, height=new_y)
(base, extension) = os.path.splitext(filename) if inplace:
newname = base + suffix + extension newname = filename
else:
suffix = '_{width}x{height}'.format(width=new_x, height=new_y)
(base, extension) = os.path.splitext(filename)
newname = base + suffix + extension
i.save(newname, quality=100) i.save(newname, quality=100)
@ -45,6 +54,7 @@ def resize_argparse(args):
args.new_y, args.new_y,
scale=args.scale, scale=args.scale,
nearest_neighbor=args.nearest_neighbor, nearest_neighbor=args.nearest_neighbor,
inplace=args.inplace,
) )
def main(argv): def main(argv):
@ -55,6 +65,7 @@ def main(argv):
parser.add_argument('new_y', nargs='?', type=int, default=None) parser.add_argument('new_y', nargs='?', type=int, default=None)
parser.add_argument('--scale', dest='scale', type=float, default=None) parser.add_argument('--scale', dest='scale', type=float, default=None)
parser.add_argument('--nearest', dest='nearest_neighbor', action='store_true') parser.add_argument('--nearest', dest='nearest_neighbor', action='store_true')
parser.add_argument('--inplace', dest='inplace', action='store_true')
parser.set_defaults(func=resize_argparse) parser.set_defaults(func=resize_argparse)
args = parser.parse_args(argv) args = parser.parse_args(argv)