- February 28, 2007
- Pre .96
- image pil thumbnail resize
- 4 (after 4 ratings)
This is a really useful function I used to create the resized preview images you can see on the homepage of my site. Basically, it takes the original URL of an image on the internet, creates a resized version of that image by fitting it into the constraints specified (doesn't distort the image), and saves it to the MEDIA_ROOT with the filename you specify.
For example, I use this by passing it the URL of a Flickr Image and letting it resize it to the required size, and then saving it to a local path. It then returns the local path to the image, should you need it. I however just construct a relative URL from the image_name and save that to the database. This way, it's easy to display this image.
Hope it's useful!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
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) # 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)