Skip to content

Instantly share code, notes, and snippets.

@pmuller
Last active May 4, 2017 04:30
Show Gist options
  • Save pmuller/ff80d2430dbb2c1245ccfb8d84806de9 to your computer and use it in GitHub Desktop.
Save pmuller/ff80d2430dbb2c1245ccfb8d84806de9 to your computer and use it in GitHub Desktop.
from io import BytesIO
from PIL import Image
def scale_image_max_width(image_bytes, max_width):
"""Scale ``image`` to honor the ``max_width`` constraint.
"""
image = Image.open(BytesIO(image_bytes))
if image.width > max_width:
factor = image.width / max_width
resized = image.resize(
(int(image.width / factor), int(image.height / factor)))
result = BytesIO()
resized.save(result, 'PNG')
result.flush()
result.seek(0)
return result.read()
else:
return image_bytes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment