Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I created a PIL Image from an in-memory file?

More specifically, I want to change the filetype of an image uploaded through a Django ImageField.

My current thinking is to created a custom ImageField and overwrite the save method to manipulate the file.

I've having trouble getting an in memory file to because a PIL Image instance.

Thanks for the help.

like image 372
Zach Avatar asked Jan 07 '11 17:01

Zach


2 Answers

Have you tried StringIO ?

see the docs http://effbot.org/imagingbook/introduction.htm#more-on-reading-images

#Reading from a string 
import StringIO

im = Image.open(StringIO.StringIO(buffer))
like image 93
Xavier Barbosa Avatar answered Oct 21 '22 21:10

Xavier Barbosa


Note that Django's ImageField inherits the open method from FieldFile. This returns a stream object that can be passed to PIL's Image.open (the standard factory method for creating Image objects from an image stream):

stream = imagefield.open()
image = Image.open(stream)
stream.close()
# ... and then save image with: image.save(outfile, format, options)

See PIL Image documentation.

like image 27
scoffey Avatar answered Oct 21 '22 21:10

scoffey