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
Tags:
image pil thumbnail resize
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. Resize image on save by David 6 years, 11 months ago
  2. Image Standarization by garcia_marc 6 years, 11 months ago
  3. Image resize on demand by VidJa 6 years, 2 months ago
  4. Better Static Image Serving With Fallback by menendez 5 years ago
  5. ImageMagick commands from Django Templates by cogat 5 years, 11 months ago

Comments

Please login first before commenting.