Login

Crop and scale image to a given size

Author:
rpw
Posted:
May 10, 2007
Language:
Python
Version:
.96
Score:
3 (after 3 ratings)

Prerequisites: Python Imaging Library

This function scales a given image (provided as binary data in any format the PIL supports) to a specified size.

If the force parameter is True, the function makes sure that the resulting image is exactly the specified size, cropping and scaling it as necessary (but never distorting it) to make sure the whole image area is filled out.

If force is False, it simply uses the thumbnail function provided by the PIL, which preserves the image aspect ratio and does not increase the image dimensions beyond those of the original file, so you may not get an image that has the exact dimensions you specified.

The result image is returned as JPEG data.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def rescale(data, width, height, force=True):
	"""Rescale the given image, optionally cropping it to make sure the result image has the specified width and height."""
	import Image as pil
	from cStringIO import StringIO
	
	max_width = width
	max_height = height

	input_file = StringIO(data)
	img = pil.open(input_file)
	if not force:
		img.thumbnail((max_width, max_height), pil.ANTIALIAS)
	else:
		src_width, src_height = img.size
		src_ratio = float(src_width) / float(src_height)
		dst_width, dst_height = max_width, max_height
		dst_ratio = float(dst_width) / float(dst_height)
		
		if dst_ratio < src_ratio:
			crop_height = src_height
			crop_width = crop_height * dst_ratio
			x_offset = float(src_width - crop_width) / 2
			y_offset = 0
		else:
			crop_width = src_width
			crop_height = crop_width / dst_ratio
			x_offset = 0
			y_offset = float(src_height - crop_height) / 3
		img = img.crop((x_offset, y_offset, x_offset+int(crop_width), y_offset+int(crop_height)))
		img = img.resize((dst_width, dst_height), pil.ANTIALIAS)
		
	tmp = StringIO()
	img.save(tmp, 'JPEG')
	tmp.seek(0)
	output_data = tmp.getvalue()
	input_file.close()
	tmp.close()
	
	return output_data

More like this

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

Comments

tiliv (on December 22, 2009):

I didn't realize that "ANTIALIAS" was available under 'pil'. Or that 'pil' was lowercase... At any rate, I borrowed your scaling algorithm for my image resizer. Many thanks for writing code that "just works"!

It's flawlessly scaling nice little images.

While I understand that 'JPEG' is a nice normalization for file format, if I were to use this snippet in an unaltered form, I'd want it to have a switch for preserving the file type.

Never can please everyone :)

#

fabian (on January 18, 2011):

Thanks for your example. While reading PIL docs I found out that you could drop lines 14 to 30 in favor of the following:

from PIL import ImageOps

img = ImageOps.fit(img, (max_width, max_height,), method=pil.ANTIALIAS)

#

Please login first before commenting.