Login

Function to create resized versions of an image from a URL and saving it to a local path

Author:
obeattie
Posted:
February 28, 2007
Language:
Python
Version:
Pre .96
Score:
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[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)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.