我有一个应该转换为jpg并保存到gridfs的png文件,我使用python的PIL lib加载文件并执行转换工作,问题是我想在保存过程中将转换后的图像存储到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而不是读取:
with fs.new_file(filename="test.png") as fp:
fp.write(fake_file.getvalue())
另外,如果您首先从StringIO的开头读取seek(0)
,则可以使用read
.
with fs.new_file(filename="test.png") as fp:
fake_file.seek(0)
fp.write(fake_file.read())