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

标签 python io gridfs stringio

我有一个 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/

相关文章:

python - SVM:使用 2 个以上特征时绘制决策面

java - Google Gson 将每个 JSON 本地文件视为字符串,即使它不是

C - 如何读取 wav 文件格式

node.js - 如何在快速 route 显示图像

python - 为什么 my_list[无 :] and my_list[:None] return my_list?

python - Django 登录不工作

python - 使用二维 numpy 数组有效填充 pandas 数据框

c++ - 如何获取文件信息/搜索目录

javascript - 很难理解 gridfs 和连接

python - 如何获取 MongoDB 存储的视频文件的剪辑?