折腾:
【未解决】Python中用Pillow去缩小分辨率以及保持画质同时最大程度压缩图片
期间,代码:
if outputFormat and (imgObj.format != outputFormat): imageBytesIO = io.BytesIO() if isOptimize: imgObj.save(imageBytesIO, outputFormat, optimize=True) else: imgObj.save(imageBytesIO, outputFormat) newImgObj = Image.open(imageBytesIO)
其中的save报错:
File "/Users/crifan/dev/dev_root/python/EvernoteToWordpress/EvernoteToWordpress/EvernoteToWordpress.py", line 565, in convertImageFormat imgObj.save(imageBytesIO, outputFormat) File "/Users/crifan/.local/share/virtualenvs/EvernoteToWordpress-PC3x4gk8/lib/python3.7/site-packages/PIL/Image.py", line 2084, in save save_handler(self, fp, filename) File "/Users/crifan/.local/share/virtualenvs/EvernoteToWordpress-PC3x4gk8/lib/python3.7/site-packages/PIL/JpegImagePlugin.py", line 621, in _save raise IOError("cannot write mode %s as JPEG" % im.mode) OSError: cannot write mode RGBA as JPEG
OSError: cannot write mode RGBA as JPEG
没太看懂,不过好像是:
im = im.convert("RGB")
然后再去save就可以了?
这里解释了:
JPG不支持alpha通道,而RGBA=Red, Green, Blue, Alpha,所以不支持RGBA
-》所以转换为RGB后,就可以保存save了。
然后去调试,果然当前图片是PNG,mode是RGBA
好像P模式也不支持?
r, g, b, a = im.split() im = Image.merge("RGB", (r, g, b))
所以,此处加上判断,手动转换
jpegNotSupportFormatList = ["RGBA", "P"] if (outputFormat == "JPEG") and (imgObj.mode in jpegNotSupportFormatList): imgObj = imgObj.convert("RGB") if isOptimize: imgObj.save(imageBytesIO, outputFormat, optimize=True) else: imgObj.save(imageBytesIO, outputFormat)
就可以了。
【总结】
pillow中,图片处理期间,用save报错:
OSError: cannot write mode RGBA as JPEG
原因:
因为JPEG本身不支持alpha(通道)
- 而RGBA=Red, Green, Blue, Alpha
- Alpha表示透明程度
- PNG格式支持RGBA
- -》JPEG不支持RGBA模式的图片
所以save时报错。
解决办法:
(把PNG等RGBA模式的图片)save成JPG之前,先转换成RGB:
jpegNotSupportFormatList = ["RGBA", "P"] if (outputFormat == "JPEG") and (imgObj.mode in jpegNotSupportFormatList): imgObj = imgObj.convert("RGB") imgObj.save(imageBytesIO, outputFormat)
即可。
转载请注明:在路上 » 【已解决】Python的pillow去save出错:OSError cannot write mode RGBA as JPEG