添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

我正在使用PIL将使用Django上传的透明PNG图片转换为JPG文件。输出看起来坏了。

源文件

透明源文件

Image.open(object.logo.path).save('/tmp/output.jpg', 'JPEG')

要么

Image.open(object.logo.path).convert('RGB').save('/tmp/output.png')

结果

两种方式的结果图像如下所示:

结果文件

有没有办法解决这个问题?我想要白色背景曾经是透明背景。

感谢出色的答案,我提出了以下函数集合:

import Image

import numpy as np

def alpha_to_color(image, color=(255, 255, 255)):

"""Set all fully transparent pixels of an RGBA image to the specified color.

This is a very simple solution that might leave over some ugly edges, due

to semi-transparent areas. You should use alpha_composite_with color instead.

Source: http://stackoverflow.com/a/9166671/284318

Keyword Arguments:

image -- PIL RGBA Image object

color -- Tuple r, g, b (default 255, 255, 255)

"""

x = np.array(image)

r, g, b, a = np.rollaxis(x, axis=-1)

r[a == 0] = color[0]

g[a == 0] = color[1]

b[a == 0] = color[2]

x = np.dstack([r, g, b, a])

return Image.fromarray(x, 'RGBA')

性能

简单的非合成alpha_to_color功能是最快的解决方案,但是由于它不能处理半透明区域,因此留下了丑陋的边框。

纯粹的PIL和numpy合成解决方案都可以提供出色的结果,但alpha_composite_with_color其速度(8.93毫秒)比pure_pil_alpha_to_color(79.6毫秒)快得多。如果您的系统上有numpy可用,那就是这种方式。 (更新:新的纯PIL版本是所有提到的解决方案中最快的。)

$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.alpha_to_color(i)"

10 loops, best of 3: 4.67 msec per loop

$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.alpha_composite_with_color(i)"

10 loops, best of 3: 8.93 msec per loop

$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.pure_pil_alpha_to_color(i)"

10 loops, best of 3: 79.6 msec per loop

$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.pure_pil_alpha_to_color_v2(i)"

10 loops, best of 3: 1.1 msec per loop

版权声明:本文为CSDN博主「weixin_39613692」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接: https://blog.csdn.net/weixin_39613692/article/details/110995474