我正在尝试使用python和pil将一些文本添加到图像中。我未能将结果图像保存为JPG。
我已经基于给出的示例 https://pillow.readthedocs.io/en/5.2.x/reference/imagedraw.html#example-draw-partial-partial-opacity-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。我究竟做错了什么?
您错过了将输出分配给结果的。在下面更改此代码
旧:
result.convert('RGB')
新:
result = result.convert('RGB')