简体   繁体   English

转换为RGB返回RGBA图像

[英]Convert to RGB returns a RGBA image

I'm trying to use Python and PIL to add some text to an image. 我正在尝试使用Python和PIL向图像添加一些文本。 I am failing on saving the resultant image as JPG. 我无法将生成的图像另存为JPG。

I've based it on the example given on https://pillow.readthedocs.io/en/5.2.x/reference/ImageDraw.html#example-draw-partial-opacity-text 我以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()

Running this prints mode after convert = RGBA which is then followed by mode after convert = RGBA运行此打印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

The image is still RGBA after the convert to RGB function. 转换为RGB功能后,图像仍为RGBA。 What am I doing wrong? 我究竟做错了什么?

You missed to assign the output to result. 您错过了将输出分配给结果。 Change this code below 在下面更改此代码

old: 旧:

result.convert('RGB')

new: 新:

result = result.convert('RGB')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM