Pillow: Guess mimetype from image bytes

Created on 10 Aug 2016  路  3Comments  路  Source: python-pillow/Pillow

I recently worked with images and needed to derive the mimetype of an image when I did not have the file name. I had the file bytes, and came up with a way to hack together a best guess mimetype:

def guess_mimetype(image_data):
    extension = ".{}".format(Image.open(StringIO.StringIO(image_data)).format)
    return mimetypes.types_map.get(extension.lower(), None)

I'm wondering if there's a place in this repo for such a feature? I looked through Image.py and I'm not sure it makes sense to go there organizationally, but if this is would be useful I can try to find a place and put in a PR.

If this doesn't belong in Pillow, is there another library where it would fit in well?

Enhancement

Most helpful comment

Fixed in #3190.

All 3 comments

I think this library does what you want:

https://github.com/ahupp/python-magic

Hi. Thanks for putting forward this idea. However, let me suggest this instead - the code that you've written relies on the static format variable. So at that rate, why don't we just add a static mimetype variable for each format? This would allow for formats that Pillow supports that are not included in Python's mimetypes, such as TGA.

Fixed in #3190.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mmalenta picture mmalenta  路  3Comments

anonymous530 picture anonymous530  路  3Comments

boskicthebrain picture boskicthebrain  路  4Comments

steph-ben picture steph-ben  路  4Comments

maxhumber picture maxhumber  路  3Comments