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