Determining if file is valid image file

André andre.roberge at
Thu Aug 2 21:48:39 CEST 2007

On Aug 2, 4:25 pm, Jarek Zgoda <jzg... at> wrote:
> André napisa³(a):
> >>>> 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.
> >>>> André
> >>> I should have added: I'm interesting in validating the file *content*
> >>> - not the filename :-)
> >> Is the module imghdr enough for your needs?
> > Yes, thanks.
> Be aware that broken images (i.e. partially downloaded) in many cases
> pass the imghdr.what() test. This function checks for patterns in files,
> just like "file" utility.

That's all I need; I'm not concerned about broken images.  I am
writing a web app and need to prevent someone using redirection to
send malicious content when I'm supposedly loading an image file.  So,
what I plan to do is open the file using urlopen, preload the image
and see if it is valid; if so, I pass it on to the browser.

To find out more, look for "redirect" on the following page (it is the
first occurence of that word)

> --
> Jarek Zgoda

More information about the Python-list mailing list