如何使用 Python Pillow 更改图像格式而不将其写入磁盘

How to change image format without writing it to disk using Python Pillow

我从网上得到了枕头图片:

response= urllib2.urlopen(<url to gif image>)
img = Image.open(cStringIO.StringIO(response.read()))

我想将它与 tesserocr 一起使用,但它不适用于 GIF 图像。

如果我将图像保存为 PNG img.save("tmp.png") 并加载它 img = Image.open("tmp.png") 一切正常。

有没有办法在不写入磁盘的情况下进行这种转换?

解决方法很简单:

response= urllib2.urlopen(<url to gif image>)
img = Image.open(cStringIO.StringIO(response.read()))
img = img.convert("RGB")

请注意,您需要删除 alpha 通道信息以使图像与 tesserocr 兼容

import io
from PIL import Image


def convertImageFormat(imgObj, outputFormat=None):
    """Convert image format
    Args:
        imgObj (Image): the Pillow Image instance
        outputFormat (str): Image format, eg: "JPEG"/"PNG"/"BMP"/"TIFF"/...
            more refer: https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html
    Returns:
        bytes, binary data of Image
    Raises:
    """
    newImgObj = imgObj
    if outputFormat and (imgObj.format != outputFormat):
        imageBytesIO = io.BytesIO()
        imgObj.save(imageBytesIO, outputFormat)
        newImgObj = Image.open(imageBytesIO)


    return newImgObj

调用示例:

pngImgFile = "xxx.png"
pngImgObj = Image.open(pngImgFile)
convertToFormat = "JPEG"
convertedJpgImgBytes = convertImageFormat(pngImgObj, convertToFormat)

高级版convertImageFormat可以参考我的libcrifanPillow.py

import io
from PIL import Image


def convertImageFormat(imgObj, outputFormat=None, isOptimize=False, isKeepPrevValues=True):
    """Convert image format
    Args:
        imgObj (Image): the Pillow Image instance
        outputFormat (str): Image format, eg: "JPEG"/"PNG"/"BMP"/"TIFF"/...
            more refer: https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html
        isOptimize (bool): do optimize when using save to convert format
        isKeepPrevValues (bool): keep previous property values, such as: filename
    Returns:
        bytes, binary data of Image
    Raises:
    """
    newImgObj = imgObj
    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)
        if isKeepPrevValues:
            if imgObj.filename:
                newImgObj.filename = imgObj.filename


    return newImgObj