如何在不使用Python Pillow将其写入磁盘的情况下更改图像格式

时间:2016-10-06 01:56:12

标签: python python-2.7 pillow cstringio

我从互联网上获得了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"),一切正常。

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

2 个答案:

答案 0 :(得分:1)

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可以参考我的库crifanPillow.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

答案 1 :(得分:0)

解决方案非常简单:

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

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