在操作JPG图像时出现“无法将模式P写入JPEG”的错误提示。

97

我正在尝试调整一些图片的大小,其中大部分是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

我不想改变图像类型,而是使用Pillow库。我的操作系统是Mac OS X。我该怎么解决这个问题?

5个回答

180

你需要将图像转换为RGB模式。

Image.open('old.jpeg').convert('RGB').save('new.jpeg')

3
我尝试将这个方法用在一个 .png 文件上,结果生成的 .jpg 文件比原文件大了 5 倍以上。 - Bentley4
@Bentley4 PNG 可以比 JPEG 更好地压缩某些类型的图像。 - davr
@Bentley4 在重采样后,您可以将其转换回 P - Maksym Ganenko

31

这个答案相当老,不过我认为我可以通过在执行转换之前检查模式来提供更好的方法:

if img.mode != 'RGB':
    img = img.convert('RGB')

这是必需的,以便将您的图像保存为JPEG格式。


这个结合当前得票最高的答案,让我的项目重新回到了正轨,谢谢! - Cfomodz

10

概述:12:

  • 背景
    • JPG 不支持 alpha = transparency
    • RGBAP 具有透明度 alpha = transparency
      • RGBA= 红绿蓝透明度
  • 结果
    • 无法将 RGBA 写入 JPEG
    • 无法将 P 写入 JPEG
  • 解决方案
    • 在保存为 JPG 前,丢弃 alpha = transparency
      • 例如:将 Image 转换为 RGB
    • 然后保存为 JPG
  • 你的代码
if im.mode == "JPEG":
    im.save("xxx.jpg")
    # in most case, resulting jpg file is resized small one
elif rgba_or_p_im.mode in ["RGBA", "P"]:
    rgb_im = rgba_or_p_im.convert("RGB")
    rgb_im.save("xxx.jpg")
    # some minor case, resulting jpg file is larger one, should meet your expectation
  • 为您做更多:

关于调整图像文件大小,我已经实现了一个函数,供您参考:

from PIL import Image, ImageDraw
cfgDefaultImageResample = Image.BICUBIC # Image.LANCZOS

def resizeImage(inputImage,
                newSize,
                resample=cfgDefaultImageResample,
                outputFormat=None,
                outputImageFile=None
                ):
    """
        resize input image
        resize normally means become smaller, reduce size
    :param inputImage: image file object(fp) / filename / binary bytes
    :param newSize: (width, height)
    :param resample: PIL.Image.NEAREST, PIL.Image.BILINEAR, PIL.Image.BICUBIC, or PIL.Image.LANCZOS
        https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.thumbnail
    :param outputFormat: PNG/JPEG/BMP/GIF/TIFF/WebP/..., more refer:
        https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html
        if input image is filename with suffix, can omit this -> will infer from filename suffix
    :param outputImageFile: output image file filename
    :return:
        input image file filename: output resized image to outputImageFile
        input image binary bytes: resized image binary bytes
    """
    openableImage = None
    if isinstance(inputImage, str):
        openableImage = inputImage
    elif CommonUtils.isFileObject(inputImage):
        openableImage = inputImage
    elif isinstance(inputImage, bytes):
        inputImageLen = len(inputImage)
        openableImage = io.BytesIO(inputImage)

    if openableImage:
        imageFile = Image.open(openableImage)
    elif isinstance(inputImage, Image.Image):
        imageFile = inputImage
    # <PIL.PngImagePlugin.PngImageFile image mode=RGBA size=3543x3543 at 0x1065F7A20>
    imageFile.thumbnail(newSize, resample)
    if outputImageFile:
        # save to file
        imageFile.save(outputImageFile)
        imageFile.close()
    else:
        # save and return binary byte
        imageOutput = io.BytesIO()
        # imageFile.save(imageOutput)
        outputImageFormat = None
        if outputFormat:
            outputImageFormat = outputFormat
        elif imageFile.format:
            outputImageFormat = imageFile.format
        imageFile.save(imageOutput, outputImageFormat)
        imageFile.close()
        compressedImageBytes = imageOutput.getvalue()
        compressedImageLen = len(compressedImageBytes)
        compressRatio = float(compressedImageLen)/float(inputImageLen)
        print("%s -> %s, resize ratio: %d%%" % (inputImageLen, compressedImageLen, int(compressRatio * 100)))
        return compressedImageBytes

最新的代码可以在这里找到:

https://github.com/crifan/crifanLibPython/blob/master/python3/crifanLib/thirdParty/crifanPillow.py


3

JPEG不支持alpha=透明度

因此,在保存为JPEG之前,必须丢弃alpha=透明度

如果你使用不同的格式,可以检查文件扩展名并特别使用转换为JPEG。

extension = str(imgName).split('.')[-1]

if extension == "png":
    bg_image.save(imgName, "PNG")
else:
    if bg_image.mode in ("RGBA", "P"):
        bg_image = bg_image.convert("RGB")
    bg_image.save(imgName, "JPEG")

0

在使用quantize()方法后遇到相同的错误。

解决方案也是相同的:转换为RGB

image.quantize(colors=256, method=2).convert('RGB')


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接