tags:

views:

3601

answers:

3

I have genereated image by PIL. How can I save it to string in memory? Image.save() method requires file.

I'd like to have number of such images stored in dictionary.

+8  A: 

You can probably use the StringIO class to get a wrapper around strings that behaves like a file. The StringIO object provides the same interface as a file, but saves the contents just in memory:

import StringIO

output = StringIO.StringIO()
image.save(output)
contents = output.getvalue()
output.close()
sth
Yes! This is exactly what I was looking for. I googled every combination of python, string, reader, writer, buffer and didn't come up with anything. Thanks!
rik.the.vik
Thanks - saved me much head scratching this morning.
Colonel Sponsz
+2  A: 

When you say "I'd like to have number of such images stored in dictionary", it's not clear if this is an in-memory structure or not.

You don't need to do any of this to meek an image in memory. Just keep the image object in your dictionary.

If you're going to write your dictionary to a file, you might want to look at im.tostring() method and the Image.fromstring() function

http://www.pythonware.com/library/pil/handbook/image.htm

im.tostring() => string

Returns a string containing pixel data, using the standard "raw" encoder.

Image.fromstring(mode, size, data) => image

Creates an image memory from pixel data in a string, using the standard "raw" decoder.

The "format" (.jpeg, .png, etc.) only matters on disk when you are exchanging the files. If you're not exchanging files, format doesn't matter.

S.Lott
It sounds like he wants to retain the PNG format, not reduce it to raw pixel data.
Ben Blank
+2  A: 

save() can take a file-like object as well as a path, so you can use an in-memory buffer like a StringIO:

buf= StringIO.StringIO()
im.save(buf, format= 'JPEG')
jpeg= buf.getvalue()
bobince
Thank you. StringIO - thats what I need.
maxp