透明PNG在转换后不保持透明度(Django + PIL)

Dan*_*erz 11 python django python-imaging-library

我在网络服务器上使用sorl-thumbnail,PILDjango来动态创建模板中的缩略图.

PIL安装时支持PNG,但由于某种原因,转换会在图像的透明部分上创建一些非常奇怪的伪像.

我在Github上使用这个要点来安装所需的依赖项:https://raw.github.com/gist/1225180/eb87ceaa7277078f17f76a89a066101ba2254391/patch.sh

以下是生成图像的模板代码(我不认为这是问题所在,但不能向您展示):

{% thumbnail project.image "148x108" crop="center" as im %}
  <img src='{{ im.url }}' />
{% endthumbnail %}
Run Code Online (Sandbox Code Playgroud)

以下是发生的事情的一个例子.任何帮助是极大的赞赏!

之前

图像透明

带有文物的图像

jte*_*ace 25

看起来您生成的图像是JPEG.JPEG格式不支持透明度.尝试将缩略图模板更改为:

{% thumbnail project.image "148x108" crop="center" format="PNG" as im %}
Run Code Online (Sandbox Code Playgroud)


vdb*_*oor 6

或者:

  • format='PNG'.
  • 添加THUMBNAIL_PRESERVE_FORMAT=True到设置.
  • 或使用此处描述的自定义引擎:

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
Run Code Online (Sandbox Code Playgroud)

在您的设置中:

THUMBNAIL_ENGINE = 'path.to.Engine'
Run Code Online (Sandbox Code Playgroud)

您现在可以使用该选项:

{% thumbnail my_file "100x100" format="JPEG" background="#333333" as thumb %}
   <img src="{{ thumb.url }}" />
{% endthumbnail %}
Run Code Online (Sandbox Code Playgroud)

  • THUMBNAIL_PRESERVE_FORMAT = True似乎是最常用的方式 (2认同)