Python 对 JPG 图像进行操作时出现“无法将模式 P 写入 JPEG”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21669657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting "cannot write mode P as JPEG" while operating on JPG image
提问by vlad halmer
I am trying to resize some images, most of which are JPG. But in a few images, I am getting the error:
我正在尝试调整一些图像的大小,其中大部分是 JPG。但在一些图像中,我收到错误:
Traceback (most recent call last):
File "image_operation_new.py", line 168, in modifyImage
tempImage.save(finalName);
File "/Users/kshitiz/.virtualenvs/django_project/lib/python2.7/site- packages/PIL/Image.py", line 1465, in save
save_handler(self, fp, filename)
File "/Users/kshitiz/.virtualenvs/django_project/lib/python2.7/site- packages/PIL/JpegImagePlugin.py", line 455, in _save
raise IOError("cannot write mode %s as JPEG" % im.mode)
IOError: cannot write mode P as JPEG
I am not changing the image type and I'm using the pillow library. My OS is Mac OS X. How can I resolve the issue?
我没有改变图像类型,我正在使用枕头库。我的操作系统是 Mac OS X。我该如何解决这个问题?
采纳答案by Jayanth Koushik
You need to convert the image to RGB mode.
您需要将图像转换为 RGB 模式。
Image.open('old.jpeg').convert('RGB').save('new.jpeg')
回答by Sarang
This answer is quite old, however, I thought I will put a better way to do the same by checking for the mode before doing the conversion:
这个答案很旧,但是,我想我会通过在转换之前检查模式来提供更好的方法来做同样的事情:
if img.mode != 'RGB':
img = img.convert('RGB')
This is required to save your image in JPEG format.
这是将图像保存为 JPEG 格式所必需的。

