python学习记录二:关于PIL处理图片缩放转存报错以及解决方案

初始运行代码如下:

from PIL import Image

# 打开一个jpg图像文件,注意是当前路径:
im = Image.open('easy2.jpg')
# 获得图像尺寸
w, h = im.size
print('Original image size: %sx%s' % (w, h))
# 缩放到50%
im.thumbnail((w//2, h//2))
print('Resize image to: %sx%s' % (w//2, h//2))
# 把缩放后的图像用jpeg格式保存
im.save('thumbnail.jpg', 'jpeg')

执行报错内容如下:

"D:\Program Files\python-3.7.9\python.exe" D:/py/test-three/test_01.py
Original image size: 680x154
Resize image to: 340x77
Traceback (most recent call last):
  File "D:\Program Files\python-3.7.9\lib\site-packages\PIL\JpegImagePlugin.py", line 630, in _save
    rawmode = RAWMODE[im.mode]
KeyError: 'RGBA'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "D:/py/test-three/test_01.py", line 13, in <module>
    im.save('thumbnail.jpg', 'jpeg')
  File "D:\Program Files\python-3.7.9\lib\site-packages\PIL\Image.py", line 2212, in save
    save_handler(self, fp, filename)
  File "D:\Program Files\python-3.7.9\lib\site-packages\PIL\JpegImagePlugin.py", line 632, in _save
    raise OSError(f"cannot write mode {im.mode} as JPEG") from e
OSError: cannot write mode RGBA as JPEG

进程已结束,退出代码1

查看报错信息以及save源代码初步断定与保存格式有关,保存png无异常,查找问题得知:png格式图片颜色为四通道RGBA,jpeg格式为三通道RGB,如要保存JPEG格式,需要转换成三通道RGB格式,即im = im.convert(‘RGB’)。【解决方案参考:https://blog.csdn.net/weixin_46256482/article/details/115733822】

另初始代码为im.save(‘thumbnail.jpg’,‘jpeg’),Windows运行下im.save(‘thumbnail.jpeg’)即可,jpg和jpeg为同一格式。
【JPEG( Joint Photographic Experts Group)即联合图像专家组,是用于连续色调静态图像压缩的一种标准,文件后缀名为.jpg或.jpeg,是最常用的图像文件格式 —from 百度百科】

修改后的代码如下:

from PIL import Image

# 打开一个jpg图像文件,注意是当前路径:
im = Image.open('easy2.jpg')
# 获得图像尺寸
w, h = im.size
print('Original image size: %sx%s' % (w, h))
# 缩放到50%
im.thumbnail((w//2, h//2))
print('Resize image to: %sx%s' % (w//2, h//2))
# 把缩放后的图像用jpeg格式保存
im = im.convert('RGB')
im.save('thumbnail.jpeg')
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值