Determining if file is valid image file

Dave Hughes dave at
Thu Aug 2 16:53:16 CEST 2007

André wrote:

> Other than installing PIL, is there a "simple" way using Python only
> to determine if a file is a valid image file?
> I'd be happy if I could at least identify valid images files for gif,
> jpeg and png.   Pointers to existing modules or examples would be
> appreciated.
> The reason why I'd prefer not using PIL is that I'd like to bundle
> such a function/module in my app.

Any reason you don't want to bundle PIL? The license looks like a
fairly standard BSD style license to me which I don't think precludes
you from bundling it (other than having to reproduce the (very small)
license text in any documentation).

Otherwise, it depends on exactly what you mean by "valid". You could do
something as simple as check the "magic" number in the header of the
file. Most image formats have something like this:

* PNG: byte sequence 89 50 4E 47 0D 0A 1A 0A
* GIF: "GIF89a" or "GIF87a"
* JPG: byte sequence FF D8 FF E0 nn nn 4A 46  49 46 00 (for JFIF)

Naturally, this won't guarantee the rest of the file is valid, but
might be sufficient for your purposes (it's one of the methods the
"file" command uses for recognizing file types).



More information about the Python-list mailing list