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

arm*_*ong 4 python io stringio gridfs

我有一个png应该转换为jpg并保存到的文件gridfs,我使用python的PILlib加载该文件并执行转换工作,问题是我想将转换后的图像存储到MongoDB Gridfs中,在保存过程中,我可以只需使用该im.save()方法。所以我用a 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:
Run Code Online (Sandbox Code Playgroud)

我对python的IO机制非常了解,如何使这项工作有效?

unu*_*tbu 5

使用getvalue方法代替read

with fs.new_file(filename="test.png") as fp:
    fp.write(fake_file.getvalue())
Run Code Online (Sandbox Code Playgroud)

另外,read如果您首先seek(0)从StringIO的开头进行读取,则可以使用。

with fs.new_file(filename="test.png") as fp:
    fake_file.seek(0)
    fp.write(fake_file.read())
Run Code Online (Sandbox Code Playgroud)