python PIL图像如何将图像保存到缓冲区以便以后使用? [英] python PIL image how to save image to a buffer so can be used later?

查看:1236
本文介绍了python PIL图像如何将图像保存到缓冲区以便以后使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a png file which should be convert to jpg and save to gridfs , I use python's PIL lib to load the file and do the converting job, the problem is I want to store the converted image to a MongoDB Gridfs, in the saving procedure, I can't just use the im.save() method. so I use a StringIO to hold the temp file but it don't work.

这里是代码片段:

#!/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:

I我在python的 IO 机制中非常青翠,如何使这个工作?

I am very verdant in python's IO mechanism, How to make this work?

推荐答案

使用 getvalue 方法而非读取

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

或者,您可以使用 如果你第一次 > seek(0) 从StringIO的开头读取。

Alternatively, you could use read if you first seek(0) to read from the beginning of the StringIO.

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

这篇关于python PIL图像如何将图像保存到缓冲区以便以后使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆