Skip to content

Instantly share code, notes, and snippets.

@jpanganiban
Created October 3, 2012 12:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpanganiban/3826675 to your computer and use it in GitHub Desktop.
Save jpanganiban/3826675 to your computer and use it in GitHub Desktop.
Scale an image by max_width and/or max_height using Wand
from wand.image import Image
def scale_image(filename, max_width=0, max_height=0, replace=False):
"""Resize an image by filename using wand (Imagemagick)
Returns tuple of filename, width and height."""
# Get filename and file format unsafely.
fname, fmat = filename.split('.')
# Create or use current filename
new_filename = filename if replace else fname + '_resized.' + fmat
with Image(filename=filename) as img:
width, height = img.size
# Skip Resize if not max_width or max_height.
if not (max_width or max_height):
return (filename, width, height)
# Skip resize if size is under max dimensions
if (width < max_width) and (height < max_height):
return (filename, width, height)
# Proceed with image resize
with img.clone() as i:
# Generate a list of scale to 1.0: 0.1, 0.2, 0.3...
for d in reversed([float(j) / float(10) for j in range(1, 11)]):
i.resize(int(i.width * d), int(i.height * d))
if max_width and max_height:
if (i.width < max_width) and (i.height < max_height):
i.save(filename=new_filename)
return (filename, i.width, i.height)
elif max_width:
if i.width < max_width:
i.save(filename=new_filename)
return (filename, i.width, i.height)
elif max_height:
if i.height < max_height:
i.save(filename=new_filename)
return (filename, i.width, i.height)
else:
i.save(filename=new_filename)
return (filename, i.width, i.height)
# Test call
print scale_image('ish.png', max_width=600, max_height=400) # 1600 x 900 image
# Returns ('ish.png', 483L, 271L), writes the new image in disk.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment