我有一个 png
文件,应该转换为 jpg
并保存到 gridfs
,我使用 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())
或者,您可以使用 read
如果你先seek(0)
从 StringIO 的开头读取。
with fs.new_file(filename="test.png") as fp:
fake_file.seek(0)
fp.write(fake_file.read())
关于python PIL图像如何将图像保存到缓冲区以便以后使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28102803/