Skip to content

Instantly share code, notes, and snippets.

@jon1012
Created March 5, 2015 09:33
Show Gist options
  • Save jon1012/c2a902f93f1fc7a3190f to your computer and use it in GitHub Desktop.
Save jon1012/c2a902f93f1fc7a3190f to your computer and use it in GitHub Desktop.
def scale_to_fit(image, frame, enlarge=False):
image_width, image_height = image
frame_width, frame_height = frame
image_aspect = float(image_width) / image_height
frame_aspect = float(frame_width) / frame_height
# Determine maximum width/height (prevent up-scaling).
if not enlarge:
max_width = min(frame_width, image_width)
max_height = min(frame_height, image_height)
else:
max_width = frame_width
max_height = frame_height
# Frame is wider than image.
if frame_aspect > image_aspect:
height = max_height
width = int(height * image_aspect)
# Frame is taller than image.
else:
width = max_width
height = int(width / image_aspect)
return (width, height)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment