In the past few months, sorl.thumbnail has become one of the standard libraries I always include in my Django projects. It’s unobstrusive and very easy to implement into templates, but my one grief with it has been the lack of capability for doing some custom processing on images. As it turns out, sorl actually allows custom processors to be added. When I found out about this feature, I set out to write some for my current project.
If you haven’t heard about the processors functionality, it’s all in the documentation. I am not sure how I missed it before. Implementing is pretty easy, first you have to define a THUMBNAIL_PROCESSORS variable in your settings.py file:
THUMBNAIL_PROCESSORS = (
'sorl.thumbnail.processors.colorspace',
'sorl.thumbnail.processors.autocrop',
'sorl.thumbnail.processors.scale_and_crop',
'sorl.thumbnail.processors.filters',
'imagery.processors.pad',
'imagery.processors.round',
)
The first four are obviously sorl’s own default processors. The last two are my custom ones. “pad” allows resizing without cropping, while keeping the final image dimensions always the same. So basically it centers the resized image in an area and fills the rest of the image with a given background colour:
from PIL import Image
THUMBNAIL_PADDING_COLOUR = (255, 255, 255)
def pad(im, requested_size, opts):
"""
Adds padding around the image to match the requested_size
"""
if "pad" in opts and im.size != requested_size:
canvas = Image.new("RGB", requested_size, THUMBNAIL_PADDING_COLOUR)
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
pad.valid_options = ("pad", )
The other one, “round”, is a bit more complex. Basically I needed a processor to add rounded corners to an image by pasting a mask on top. Since it’s not possible to pass parameters to a processor, I ended up having a method that can take one of a few rounding options and use the actual name of the option to find the correct mask file:
ROUND_VALID_OPTIONS = (
"round",
"round-box",
"round-wide",
)
def round(im, requested_size, opts):
"""
Adds rounded corners around the image
"""
try:
mask_type = filter(lambda x: x in ROUND_VALID_OPTIONS, opts)[0]
except IndexError:
mask_type = None
if mask_type:
mask = Image.open(os.path.join(THUMBNAIL_ROUND_MASKS_PATH, "%s.png" % mask_type))
im.paste(mask, (0, 0), mask)
return im
round.valid_options = ROUND_VALID_OPTIONS
This makes sorl indispensable for me!
sorl-thumbnail really is indispensable. I’ve been using it without any integration issues for a month or so. I’m amazed at how easily it plugged in to my apps.
Yes! I use this lib to deal with all the thumb jobs.
© Copyright 2001-2010 Taylan Pince. All rights reserved.
You might want to check out django-imagekit. It also support custom processors. http://bitbucket.org/jdriscoll/django-imagekit/