Created
October 3, 2012 12:26
-
-
Save jpanganiban/3826675 to your computer and use it in GitHub Desktop.
Scale an image by max_width and/or max_height using Wand
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
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