第一句子网 - 唯美句子、句子迷、好句子大全
第一句子网 > python rgba_使用PIL将RGBA PNG转换为RGB

python rgba_使用PIL将RGBA PNG转换为RGB

时间:2020-11-22 09:45:20

相关推荐

python rgba_使用PIL将RGBA PNG转换为RGB

我正在使用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: /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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。