我正在使用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 Imageimport numpy as npdef 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
添加回答
举报
0/150
提交
取消