如何在不使用Python将图像写入磁盘的情况下更改图像格式
我从网上得到的枕头图片:如何在不使用Python将图像写入磁盘的情况下更改图像格式,python,python-2.7,pillow,cstringio,Python,Python 2.7,Pillow,Cstringio,我从网上得到的枕头图片: response= urllib2.urlopen(<url to gif image>) img = Image.open(cStringIO.StringIO(response.read())) response=urllib2.urlopen() img=Image.open(cStringIO.StringIO(response.read())) 我想与tesserocr一起使用,但它不能与GIF图像一起使用 如果我将图像保存为PNGimg.sa
response= urllib2.urlopen(<url to gif image>)
img = Image.open(cStringIO.StringIO(response.read()))
response=urllib2.urlopen()
img=Image.open(cStringIO.StringIO(response.read()))
我想与tesserocr一起使用,但它不能与GIF图像一起使用
如果我将图像保存为PNGimg.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")
response=urllib2.urlopen()
img=Image.open(cStringIO.StringIO(response.read()))
img=img.convert(“RGB”)
请注意,您需要删除alpha通道信息,以使图像与tesserocr兼容
从PIL导入图像
def convertImageFormat(imgObj,outputFormat=None):
“”“转换图像格式
Args:
imgObj(图像):枕头图像实例
outputFormat(str):图像格式,例如:“JPEG”/“PNG”/“BMP”/“TIFF”/。。。
更多信息请参阅:https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html
返回:
字节,图像的二进制数据
提出:
"""
newImgObj=imgObj
如果outputFormat和(imgObj.format!=outputFormat):
imageBytesIO=io.BytesIO()
imgObj.save(imageBytesIO,outputFormat)
newImgObj=Image.open(imageBytesIO)
返回newImgObj
呼叫示例:
pngImgFile=“xxx.png”
pngImgObj=Image.open(pngImgFile)
convertToFormat=“JPEG”
convertedJpgImgBytes=convertImageFormat(pngImgObj,convertToFormat)
高级版本convertImageFormat
可以参考我的库
导入io
从PIL导入图像
def convertImageFormat(imgObj,outputFormat=None,isOptimize=False,isKeepPrevValues=True):
“”“转换图像格式
Args:
imgObj(图像):枕头图像实例
outputFormat(str):图像格式,例如:“JPEG”/“PNG”/“BMP”/“TIFF”/。。。
更多信息请参阅:https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html
等参优化(bool):使用保存转换格式时进行优化
isKeepPrevValues(bool):保留以前的属性值,例如:filename
返回:
字节,图像的二进制数据
提出:
"""
newImgObj=imgObj
如果outputFormat和(imgObj.format!=outputFormat):
imageBytesIO=io.BytesIO()
如果进行优化:
imgObj.save(imageBytesIO,outputFormat,optimize=True)
其他:
imgObj.save(imageBytesIO,outputFormat)
newImgObj=Image.open(imageBytesIO)
如果isKeepPrevValues:
如果imgObj.filename:
newImgObj.filename=imgObj.filename
返回newImgObj