python PIL image how to save image to a buffer so can be used later?

拥有回忆 提交于 2020-01-21 07:49:05

问题


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.

here is the code snippet:

#!/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 am very verdant in python's IO mechanism, How to make this work?


回答1:


Use the getvalue method instead of read:

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

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())


来源:https://stackoverflow.com/questions/28102803/python-pil-image-how-to-save-image-to-a-buffer-so-can-be-used-later

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!