Skip to content

Instantly share code, notes, and snippets.

@davidwtbuxton
Created November 23, 2012 10:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save davidwtbuxton/4135069 to your computer and use it in GitHub Desktop.
Save davidwtbuxton/4135069 to your computer and use it in GitHub Desktop.
Demonstrates logic bug in scaling function
# 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