def create_resized_image(image_name, original_location, xconstrain=200, yconstrain=200): """ Takes an input URL for an image, a name for the image for it to be saved as, and the optional xconstrain and yconstrain options, which are used to define the constraints to resize the image to. If these are not specified, they will default to 200px each. Returns the path to the image """ from PIL import Image, ImageOps import urllib import os from django.conf import settings if not os.path.exists('%s/images/resized/%s.jpg' % (settings.MEDIA_ROOT, image_name)): # Ensure a resized image doesn't already exist in the default MEDIA_ROOT/images/resized (MEDIA_ROOT is defined in Django's settings) unsized_image = urllib.urlretrieve(str(original_location)) # Fetch original image unsized_image = Image.open(unsized_image[0]) # Load the fetched image resized_image = ImageOps.fit(unsized_image, (xconstrain, yconstrain), Image.ANTIALIAS) # Create a resized image by fitting the original image into the constrains, and do this using proper antialiasing resized_image = resized_image.convert("RGB") # PIL sometimes throws errors if this isn't done resized_image.save('%s/images/resized/%s.jpg' % (settings.MEDIA_ROOT, image_name), 'jpeg') # Save the resized image as a jpeg into the MEDIA_ROOT/images/resized return '%s/images/resized/%s.jpg' % (settings.MEDIA_ROOT, image_name)