小编Car*_*l H的帖子

转换为 RGB 返回 RGBA 图像

我正在尝试使用 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()
Run Code Online (Sandbox Code Playgroud)

运行此打印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 …
Run Code Online (Sandbox Code Playgroud)

python python-imaging-library

4
推荐指数
1
解决办法
9337
查看次数

标签 统计

python ×1

python-imaging-library ×1