Finding MIME type for a data stream
d at davea.name
Thu Mar 8 23:56:36 CET 2012
On 03/08/2012 05:28 PM, Tobiah wrote:
> I should simplify my question. Let's say I have a string
> that contains image data called 'mystring'.
> I want to do
> mime_type = some_magic(mystring)
> and get back 'image/jpg' or 'image/png' or whatever is
> appropriate for the image data.
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.
Anyway, I don't know any way in the standard lib to distinguish
arbitrary image formats. (There very well could be one.) The file
program I referred to was an external utility, which you could run with
the multiprocessing module.
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. For example, a standard zip file
starts with "PK" for Phil Katz. A Windows exe starts with "MZ" for
Mark Zbikowsky. And I believe a jpeg file starts hex(d8) (ff) (e0) (ff)
If you'd like to see a list of available modules, help() is your
friend. You can start with help("modules") to see quite a long list.
And I was surprised how many image related things already are there. So
maybe there's something I don't know about that could help.
More information about the Python-list