【发布时间】:2019-06-27 02:20:18
【问题描述】:
我正在尝试使用 Python 和 PIL 向图像添加一些文本。我无法将生成的图像保存为 JPG。
我基于给出的示例 https://pillow.readthedocs.io/en/5.2.x/reference/ImageDraw.html#example-draw-partial-opacity-text
from PIL import Image, ImageDraw, ImageFont
def example():
base = Image.open('test.jpg').convert('RGBA')
txt = Image.new('RGBA', base.size, (255,255,255,0))
fnt = ImageFont.truetype('/Library/Fonts/Chalkduster.ttf', 40)
drw = ImageDraw.Draw(txt)
drw.text((10,10), "HELLO", font=fnt, fill=(255,0,0,128))
result= Image.alpha_composite(base, txt)
result.convert('RGB')
print ('mode after convert = %s'%result.mode)
result.save('test1.jpg','JPEG')
example()
运行此打印mode after convert = RGBA
然后是
Traceback (most recent call last):
File "/Users/carl/miniconda3/envs/env0/lib/python3.7/site-packages/PIL/JpegImagePlugin.py", line 620, in _save
rawmode = RAWMODE[im.mode]
KeyError: 'RGBA'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "example.py", line 14, in <module>
example()
File "example.py", line 12, in example
result.save('test1.jpg','JPEG')
File "/Users/carl/miniconda3/envs/env0/lib/python3.7/site-packages/PIL/Image.py", line 2007, in save
save_handler(self, fp, filename)
File "/Users/carl/miniconda3/envs/env0/lib/python3.7/site-packages/PIL/JpegImagePlugin.py", line 622, in _save
raise IOError("cannot write mode %s as JPEG" % im.mode)
OSError: cannot write mode RGBA as JPEG
转换为 RGB 功能后,图像仍然是 RGBA。 我究竟做错了什么?
【问题讨论】:
-
请给我们您的 test.jpg。谢谢
-
我不太确定,你的代码的动机是什么?就像您想创建部分不透明文本,然后您尝试将输出图像保存为
RGB颜色模式,这摆脱了图像的 Alpha 通道。因此,在图像转换为 RGB 后,您将失去图像的所有不透明度。 -
@VasuDeo.S 我只想在照片上添加一些文字。
-
那么,为什么是部分不透明呢?它只是图像的叠加。如果没有
composite()函数,您可以简单地做到这一点。由于您在问题中提供的链接是针对部分不透明度的,其中输出图像中将包含不同不透明度的文本,而不是完全没有不透明度的文本。 -
@VasuDeo.S 我将我的实际代码缩减为尽可能小的示例来演示我的问题。感谢您提供有关不透明度的信息。
标签: python python-imaging-library