Discuss / Python / 关于第一个示例代码运行报错修改以及记录

关于第一个示例代码运行报错修改以及记录

Topic source

#1 Created at ... [Delete] [Delete and Lock User]

Windows下正确运行代码如下:

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') 

关于原示例代码报错如下:

"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')。

另示例代码为im.save('thumbnail.jpg',‘jpeg’),Windows运行下im.save('thumbnail.jpeg')即可


  • 1

Reply