Create a gist now

Instantly share code, notes, and snippets.

Automatic thumbnail format for Sorl - see http://gregbrown.co.nz/code/sorl-thumbnail-auto-format/
#!/usr/bin/python
from sorl.thumbnail.conf import settings
from sorl.thumbnail.base import ThumbnailBackend
FORMAT_DICT = {
'png': 'PNG',
'jpeg': 'JPEG',
'jpg': 'JPEG',
}
class AutoFormatBackend(ThumbnailBackend):
def get_thumbnail(self, file_, geometry_string, **options):
"""
Sets the format option (if not explicitly set) to the same format as the
original file.
"""
if not options.get('format'):
ext = str(file_).split('.')[-1].lower()
options['format'] = FORMAT_DICT.get(ext, settings.THUMBNAIL_FORMAT)
return super(AutoFormatBackend, self).get_thumbnail(file_, geometry_string, **options)

Usage

Place sorl_backends.py on your path, and add the following to your django settings.

THUMBNAIL_BACKEND = 'sorl_backends.AutoFormatBackend'

# this is still used if the format cannot be automatically inferred (eg for a .gif image)
THUMBNAIL_FORMAT = 'JPEG'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment