最新消息:20210917 已从crifan.com换到crifan.org

【已解决】Python的pillow去save出错:OSError cannot write mode RGBA as JPEG

Write crifan 576浏览 0评论
折腾:
【未解决】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
cannot write mode RGBA as JPEG (4.2.0) · Issue #2609 · python-pillow/Pillow · GitHub
没太看懂,不过好像是:
im = im.convert("RGB")
然后再去save就可以了?
python – Convert png to jpeg using Pillow – Stack Overflow
python 3.6 – cannot write mode RGBA as JPEG – Stack Overflow
这里解释了:
JPG不支持alpha通道,而RGBA=Red, Green, Blue, Alpha,所以不支持RGBA
-》所以转换为RGB后,就可以保存save了。
然后去调试,果然当前图片是PNG,mode是RGBA
python – Image Conversion – Cannot write mode RGBA as JPEG – Stack Overflow
好像P模式也不支持?
PIL PNG格式通道问题的解决方法 – 林深时见鹿 – 博客园
     r, g, b, a = im.split()
     im = Image.merge("RGB", (r, g, b))
python 3.6 – cannot write mode RGBA as JPEG – Stack Overflow
所以,此处加上判断,手动转换
        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

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
90 queries in 0.204 seconds, using 23.35MB memory