25👍
It looks like your resulting image is a JPEG. The JPEG format does not support transparency. Try changing your thumbnail template to this:
{% thumbnail project.image "148x108" crop="center" format="PNG" as im %}
6👍
Either:
- add
format='PNG'
. - add
THUMBNAIL_PRESERVE_FORMAT=True
to the settings. - or use the custom engine as described here:
http://yuji.wordpress.com/2012/02/26/sorl-thumbnail-convert-png-to-jpeg-with-background-color/
"""
Sorl Thumbnail Engine that accepts background color
---------------------------------------------------
Created on Sunday, February 2012 by Yuji Tomita
"""
from PIL import Image, ImageColor
from sorl.thumbnail.engines.pil_engine import Engine
class Engine(Engine):
def create(self, image, geometry, options):
thumb = super(Engine, self).create(image, geometry, options)
if options.get('background'):
try:
background = Image.new('RGB', thumb.size, ImageColor.getcolor(options.get('background'), 'RGB'))
background.paste(thumb, mask=thumb.split()[3]) # 3 is the alpha of an RGBA image.
return background
except Exception, e:
return thumb
return thumb
in your settings:
THUMBNAIL_ENGINE = 'path.to.Engine'
You can use the option now:
{% thumbnail my_file "100x100" format="JPEG" background="#333333" as thumb %}
<img src="{{ thumb.url }}" />
{% endthumbnail %}
- Custom field's to_python not working? – Django
- Django – links generated with {% url %} – how to make them secure?
- How to profile Django on Gunicorn in production
- Got AttributeError when attempting to get a value for field on serializer
- Is it possible to force queryset evaluation while keeping it a queryset
1👍
I’d suggest you rather look into how sorl’s PIL backend handles scaling. I imagine it creates some helper image to apply additional effects on and then tells PIL to scale the original onto that. You need to make sure that the destination is using the RGBA
mode to support transparency and that it starts with its alpha set to zero (and not pure white or pitch black or something similar). If your image is using an indexed palette then it’s possible it does not get converted to RGBA
. In indexed mode PNGs store the transparent color index in their metadata but the process of creating the thumbnail will alter pixels due to antialiasing so you cannot preserve indexed transparency in:
source = Image.open('dead-parrot.png')
source.convert('RGBA')
dest = source.resize((100, 100), resample=Image.ANTIALIAS)
dest.save('ex-parrot.png')