Created
November 23, 2012 10:44
-
-
Save davidwtbuxton/4135069 to your computer and use it in GitHub Desktop.
Demonstrates logic bug in scaling function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Test for scaling function. Python 2.7. | |
# http://www.nerdydork.com/django-custom-upload-handler-to-compress-image-files.html | |
def scale_dimensions(width, height, longest_side): | |
if width > longest_side: | |
ratio = longest_side * 1. / width | |
return (int(width * ratio), int(height * ratio)) | |
elif height > longest_side: | |
ratio = longest_side * 1. / height | |
return (int(width * ratio), int(height * ratio)) | |
return (width, height) | |
def scale_dimensions2(width, height, longest_side): | |
if width <= longest_side and height <= longest_side: | |
return width, height | |
# Force a float to avoid integer division rounding. | |
ratio = float(width) / height | |
# Landscape | |
if ratio > 1: | |
return longest_side, longest_side / ratio | |
# Portrait | |
else: | |
return longest_side * ratio, longest_side | |
tests = [ | |
# Width, height, longest side | |
(800, 600, 500), | |
(600, 800, 500), # scale_dimensions gives 500 x 666! | |
(800, 600, 700), | |
(600, 800, 700), | |
(100, 100, 200), | |
] | |
for idx, (w, h, m) in enumerate(tests): | |
w2, h2 = scale_dimensions(w, h, m) | |
w3, h3 = scale_dimensions2(w, h, m) | |
print "{idx}: {} x {}, fit to {}".format(w, h, m, idx=idx) | |
print " {idx}a: {} x {} {idx}b: {} x {}".format(w2, h2, w3, h3, idx=idx) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment