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

armnotstrong picture armnotstrong · Jan 23, 2015 · Viewed 7.9k times · Source

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?

Answer

unutbu picture unutbu · Jan 23, 2015

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