python PIL图像如何将图像保存到缓冲区以便以后使用?

python PIL image how to save image to a buffer so can be used later?

我有一个 png 文件应该转换为 jpg 并保存到 gridfs ,我使用 python 的 PIL 库来加载文件并进行转换工作,问题是我想将转换后的图像存储到 MongoDB Gridfs,在保存过程中,我不能只使用 im.save() 方法。所以我使用 StringIO 来保存临时文件,但它不起作用。

这是代码片段:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from PIL import Image
from pymongo import MongoClient
import gridfs
from StringIO import StringIO


im = Image.open("test.png").convert("RGB")

#this is what I tried, define a 
#fake_file with StringIO that stored the image temporarily.
fake_file = StringIO()
im.save(fake_file,"jpeg")

fs = gridfs.GridFS(MongoClient("localhost").stroage)

with fs.new_file(filename="test.png") as fp:
    # this will not work
    fp.write(fake_file.read())


# vim:ai:et:sts=4:sw=4:

我对python的IO机制非常熟悉,如何使它起作用?

使用 getvalue method 代替 read:

with fs.new_file(filename="test.png") as fp:
    fp.write(fake_file.getvalue())

或者,您可以使用 read if you first seek(0) 从 StringIO 的开头读取。

with fs.new_file(filename="test.png") as fp:
    fake_file.seek(0)
    fp.write(fake_file.read())