我正在尝试使用Python和PIL向图像添加一些文本。 我在将结果图像保存为JPG时失败了。
我基于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()
运行此代码会打印出
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格式。我做错了什么?
RGB
颜色模式保存输出图像,这会消除图像的Alpha通道。因此,在将图像转换为RGB后,您将失去所有的图像不透明度。 - Vasu Deo.Scomposite()
函数的情况下完成它。正如你在问题中提供的链接所示,部分不透明度会使输出图像中的文本具有不同的不透明度,而不是完全没有不透明度的文本。 - Vasu Deo.S