Login

Letterbox for sorl-thumbnail

Author:
Mogga
Posted:
April 7, 2009
Language:
Python
Version:
1.0
Score:
0 (after 0 ratings)

This custom processor is meant for use with sorl-thumbnail to add letterboxing functionality. Add to your THUMBNAIL_PROCESSORS like so:

THUMBNAIL_PROCESSORS = ( 'sorl.thumbnail.processors.colorspace', 'sorl.thumbnail.processors.autocrop', 'sorl.thumbnail.processors.scale_and_crop', 'sorl.thumbnail.processors.filters', # custom processors 'utils.processors.ltbx', )

and then use in your templates like so:

{% thumbnail model.img_field 200x150 ltbx as thumb %} <img src="{{ thumb }}" width="{{ thumb.width }}" height="{{ thumb.height }}" />

Enjoy.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
def ltbx(im, requested_size, opts):
	img_x, img_y   = [float(v) for v in im.size]
	dest_x, dest_y = [float(v) for v in requested_size]

	if 'ltbx' in opts and im.size != requested_size:
		img_ratio = img_x/img_y
		dest_ratio = dest_x/dest_y
		if dest_ratio > img_ratio:
			im = im.resize(( int(dest_y*img_ratio), dest_y ) , resample=Image.ANTIALIAS)
		else:
			im = im.resize(( dest_x, int(dest_x/img_ratio) ) , resample=Image.ANTIALIAS)
		canvas = Image.new("RGB", requested_size, THUMBNAIL_PADDING_COLOR)
		left = floor((requested_size[0] - im.size[0]) / 2)
		top = floor((requested_size[1] - im.size[1]) / 2)
		canvas.paste(im, (left, top))
		im = canvas
 
	return im

ltbx.valid_options = ('ltbx', )

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.