# HG changeset patch # User Paul Boddie # Date 1444603522 -7200 # Node ID c37a282541e392007747a5b881773b2cbe195aec # Parent 4a75d044c6447b4e2ffa34589498f08f098e9d20 Fixed scaling calculations; added explicit support to preserve the aspect ratio. diff -r 4a75d044c644 -r c37a282541e3 optimiser.py --- a/optimiser.py Sun Oct 11 23:23:26 2015 +0200 +++ b/optimiser.py Mon Oct 12 00:45:22 2015 +0200 @@ -112,6 +112,8 @@ -W - Indicate the output width (default is 320) -C - Number of colours per scanline (default is 4) +-A - Produce an output image with the same aspect ratio as the input + (useful for previewing) -s - Saturate the input image (optional float, 1.0 if unspecified) -d - Desaturate the input image (optional float, 1.0 if unspecified) @@ -133,8 +135,8 @@ """ % split(sys.argv[0])[1] sys.exit(1) - base_width = 320 - height = 256 + base_width = width = 320 + base_height = height = 256 input_filename, output_filename = sys.argv[1:3] basename, ext = splitext(output_filename) @@ -146,6 +148,10 @@ width = get_parameter(options, "-W", int, base_width, base_width) number_of_colours = get_parameter(options, "-C", int, 4, 4) + preserve_aspect_ratio = "-A" in options + + scale_factor = float(width) / base_width + height = int(base_height * scale_factor) # Preprocessing options that employ parameters. @@ -169,12 +175,13 @@ if make_image or preview: exif = EXIF.process_file(open(input_filename)) im = PIL.Image.open(input_filename).convert("RGB") - im = rotate_and_scale(exif, im, base_width, height, rotate) + im = rotate_and_scale(exif, im, width, height, rotate) + image_width, image_height = im.size - # Scale images to the appropriate width. + # Scale images to the appropriate height. - if width != base_width: - im = im.resize((width, height)) + if scale_factor != 1: + im = im.resize((image_width, int(image_height / scale_factor))) process_image(im, saturate, desaturate, darken, brighten) @@ -183,16 +190,28 @@ if preview: imp = im.copy() if half_resolution_preview: - imp = imp.resize((width / 2, height)) + imp = imp.resize((image_width / 2, image_height)) convert_image(imp, 8) if half_resolution_preview: - imp = imp.resize((width, height)) + imp = imp.resize((image_width, image_height)) + + # Scale images to a height determined by the aspect ratio. + + if preserve_aspect_ratio and scale_factor != 1: + imp = imp.resize((image_width, image_height)) + imp.save(preview_filename) # Generate an output image if requested. if make_image: convert_image(im, number_of_colours, least_error) + + # Scale images to a height determined by the aspect ratio. + + if preserve_aspect_ratio and scale_factor != 1: + im = im.resize((image_width, image_height)) + im.save(output_filename) # Verify the output image (which may be loaded) if requested.