BytesIO
类来获取一个字符串的包装器,它的行为像一个文件。 BytesIO
对象提供与文件相同的接口,但将内容保存在内存中:import io
with io.BytesIO() as output:
image.save(output, format="GIF")
contents = output.getvalue()
您需要使用format
参数显式指定输出格式,否则当PIL尝试自动检测时,它会引发错误。
如果您从文件加载图像,则具有包含原始文件格式的format
属性,因此在这种情况下,您可以使用format=image.format
。
在Python 2旧版本中,在引入io
模块之前,您将使用StringIO
模块。
对于Python3,需要使用BytesIO:
from io import BytesIO
from PIL import Image, ImageDraw
image = Image.new("RGB", (300, 50))
draw = ImageDraw.Draw(image)
draw.text((0, 0), "This text is drawn on image")
byte_io = BytesIO()
image.save(byte_io, 'PNG')
阅读更多:http://fadeit.dk/blog/post/python3-flask-pil-in-memory-image
sth的解决方案对我没有用,因为在……
Imaging/PIL/Image.pyc第1423行 -> raise KeyError(ext)#未知扩展名
它试图从文件名的扩展名检测格式,在StringIO情况下不存在。
您可以通过设置参数中的格式来绕过格式检测。
import StringIO
output = StringIO.StringIO()
format = 'PNG' # or 'JPEG' or whatever you want
image.save(output, format)
contents = output.getvalue()
output.close()
save()
方法不仅可以接受文件路径作为参数,还可以接受类似于StringIO
的内存缓冲区对象:
buf = StringIO.StringIO()
im.save(buf, format='JPEG')
jpeg = buf.getvalue()
使用现代(截至2017年中期的Python 3.5和Pillow 4.0):
StringIO不再起作用,BytesIO类是处理此问题的正确方法。 Pillow的保存函数将字符串作为第一个参数,令人惊讶的是不将StringIO视为字符串。以下内容类似于旧的StringIO解决方案,但使用BytesIO代替。
from io import BytesIO
from PIL import Image
image = Image.open("a_file.png")
faux_file = BytesIO()
image.save(faux_file, 'png')
image
对象保存在您的字典中即可。im.tostring()
方法和Image.fromstring()
函数。
http://effbot.org/imagingbook/image.htm
“格式”(.jpeg、.png等)仅在交换文件时才在磁盘上起作用。如果您不交换文件,则格式无关紧要。im.tostring() => string
返回包含像素数据的字符串,使用标准的“原始”编码器。
Image.fromstring(mode, size, data) => image
从字符串中的像素数据创建图像内存,使用标准的“原始”解码器。
-> raise KeyError(ext) # 未知扩展名 - tabdulradi
您可以使用文件对象而不是文件名。在这种情况下,您必须始终指定格式。
因此,如果第一个参数是文件对象,您必须传递第二个参数,即格式(例如'PNG'
)。 - Su Zhangfrom io import StringIO
。 - Spoutnik16image.save(output, format=image.format)
。 - reetesh11