繁体   English   中英

如何使用 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")一切正常。

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

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可以参考我的 lib 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

解决方案非常简单:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM