Finding MIME type for a data stream

Jon Clements joncle at googlemail.com
Fri Mar 9 03:31:22 CET 2012


On Thursday, 8 March 2012 23:40:13 UTC, Tobiah  wrote:
> > I have to assume you're talking python 2, since in python 3, strings 
> > cannot generally contain image data.  In python 2, characters are pretty 
> > much interchangeable with bytes.
> 
> Yeah, python 2
> 
> 
> > if you're looking for a specific, small list of file formats, you could 
> > make yourself a signature list.  Most (not all) formats distinguish 
> > themselves in the first few bytes. 
> 
> Yeah, maybe I'll just do that.  I'm alowing users to paste
> images into a rich-text editor, so I'm pretty much looking 
> at .png, .gif, or .jpg.  Those should be pretty easy to 
> distinguish by looking at the first few bytes.  
> 
> Pasting images may sound weird, but I'm using a jquery
> widget called cleditor that takes image data from the
> clipboard and replaces it with inline base64 data.  
> The html from the editor ends up as an email, and the
> inline images cause the emails to be tossed in the
> spam folder for most people.  So I'm parsing the
> emails, storing the image data, and replacing the
> inline images with an img tag that points to a 
> web2py app that takes arguments that tell it which 
> image to pull from the database.  
> 
> Now that I think of it, I could use php to detect the
> image type, and store that in the database.  Not quite
> as clean, but that would work.
> 
> Tobiah

Something like the following might be worth a go:
(untested)

from PIL import Image
img = Image.open(StringIO(blob))
print img.format

HTH
Jon.

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



More information about the Python-list mailing list