python pillow OSError: cannot write mode RGBA as JPEG
前言
Traceback (most recent call last):
File “G:\od15\venv\lib\site-packages\PIL\JpegImagePlugin.py”, line 610, in _save
rawmode = RAWMODE[im.mode]
KeyError: ‘RGBA’
The above exception was the direct cause of the following exception:
OSError: cannot write mode RGBA as JPEG
一、保存失败原因
在运行过程中,出现错误
OSError: cannot write mode RGBA as JPEG
原因:我的图像文件中有png格式的。
查资料发现是PNG有RGBA四个通道,而JPG是RGB三个通道,所以PNG转BMP时候程序不知道A通道怎么办,就会产生错误。
解决方法就是检查通道数,舍弃A通道。解决在代码中加入
# 打开图片
my_image = Image.open(fp+'\\'+fileName)
r, g, b, a = my_image.split()
my_image = Image.merge("RGB", (r, g, b))
结果:
r, g, b, a = my_image.split()
ValueError: not enough values to unpack (expected 4, got 3)