【问题标题】:Transparent PNGs don't retain transparency after being transformed (Django + PIL)透明PNG在转换后不保持透明度(Django + PIL)
【发布时间】:2011-09-26 21:56:05
【问题描述】:

我在网络服务器上使用sorl-thumbnailPILDjango 在模板中动态创建缩略图。

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

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

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

{% thumbnail project.image "148x108" crop="center" as im %}
  <img src='{{ im.url }}' />
{% endthumbnail %}

下面是一个例子。非常感谢任何帮助!

之前

之后

【问题讨论】:

  • 您使用的是哪个 sorl-thumbnail 后端?

标签: python django python-imaging-library


【解决方案1】:

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

{% thumbnail project.image "148x108" crop="center" format="PNG" as im %}

【讨论】:

    【解决方案2】:

    要么:

    • 添加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
    

    在您的设置中:

    THUMBNAIL_ENGINE = 'path.to.Engine'
    

    您现在可以使用该选项:

    {% thumbnail my_file "100x100" format="JPEG" background="#333333" as thumb %}
       <img src="{{ thumb.url }}" />
    {% endthumbnail %}
    

    【讨论】:

    • THUMBNAIL_PRESERVE_FORMAT=True 似乎是最简单的方法
    • format='PNG' 为我工作...一旦我还记得禁用浏览器缓存,因此我之前失败的上传尝试没有继续出现。
    【解决方案3】:

    我建议您研究一下 sorl 的 PIL 后端如何处理缩放。我想它会创建一些辅助图像来应用附加效果,然后告诉 PIL 将原始图像缩放到该图像上。您需要确保目标使用RGBA 模式来支持透明度,并且它的alpha 设置为零(而不是纯白色或纯黑色或类似的东西)。如果您的图像使用索引调色板,则它可能不会转换为RGBA。在索引模式下,PNG 将透明颜色索引存储在其元数据中,但创建缩略图的过程会由于抗锯齿而改变像素,因此您无法在以下位置保留索引透明度:

    source = Image.open('dead-parrot.png')
    source.convert('RGBA')
    dest = source.resize((100, 100), resample=Image.ANTIALIAS)
    dest.save('ex-parrot.png')
    

    【讨论】:

      猜你喜欢
      • 2013-04-11
      • 1970-01-01
      • 1970-01-01
      • 2012-05-29
      • 1970-01-01
      • 2012-03-29
      • 2021-10-03
      • 2020-07-12
      • 2014-09-04
      相关资源
      最近更新 更多