簡體   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