Login

resize to thumbnail with scale-to-fill

Author:
rennat
Posted:
September 30, 2008
Language:
Python
Version:
1.0
Score:
0 (after 0 ratings)

So you can upload rectangular pictures but still have square thumbnails.

"Scale to fill" instead of the out of the box "scale to fit" you get with Image.thumbnail

 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from PIL import Image
from django.db import models

class Photo(models.Model):
	photo = models.ImageField(upload_to='photos')
	
	def save(self, size=(200, 200)):
		"""
			REQUIRES:
				1.	'from PIL import Image'
			
			DOES:
				1.	check to see if the image needs to be resized
				2.	check how to resize the image based on its aspect ratio
				3.	resize the image accordingly
			
			ABOUT:
				based loosely on djangosnippet #688
				http://www.djangosnippets.org/snippets/688/
			
			VERSIONS I'M WORKING WITH:
				Django 1.0
				Python 2.5.1
			
			BY:
				Tanner Netterville
				[email protected]
		"""
		
		if not self.id and not self.photo:
			return
		
		super(Photo, self).save()
		
		pw = self.photo.width
		ph = self.photo.height
		nw = size[0]
		nh = size[1]
		
		# only do this if the image needs resizing
		if (pw, ph) != (nw, nh):
			filename = str(self.photo.path)
			image = Image.open(filename)
			pr = float(pw) / float(ph)
			nr = float(nw) / float(nh)
			
			if pr > nr:
				# photo aspect is wider than destination ratio
				tw = int(round(nh * pr))
				image = image.resize((tw, nh), Image.ANTIALIAS)
				l = int(round(( tw - nw ) / 2.0))
				image = image.crop((l, 0, l + nw, nh))
			elif pr < nr:
				# photo aspect is taller than destination ratio
				th = int(round(nw / pr))
				image = image.resize((nw, th), Image.ANTIALIAS)
				t = int(round(( th - nh ) / 2.0))
				print((0, t, nw, t + nh))
				image = image.crop((0, t, nw, t + nh))
			else:
				# photo aspect matches the destination ratio
				image = image.resize(size, Image.ANTIALIAS)
				
			image.save(filename)

More like this

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

Comments

Please login first before commenting.