Wiz
Wiz

Reputation: 4865

Python determine file type from http form submission

I want to do an image form submission, and I want to validate that the image was submitted is an image server side, which is running python. Is there a simple way to do this in pure python?

Upvotes: 0

Views: 195

Answers (2)

the wolf
the wolf

Reputation: 35522

Use PIL:

import sys
import Image

for infile in sys.argv[1:]:
    try:
        im = Image.open(infile)
        print infile, im.format, "%dx%d" % im.size, im.mode
    except IOError:
        pass

From the docs:

The Python Imaging Library supports a wide variety of image file formats. To read files from disk, use the open function in the Image module. You don't have to know the file format to open a file. The library automatically determines the format based on the contents of the file.

Upvotes: 1

gcbirzan
gcbirzan

Reputation: 1514

A simple and naive way to do it would be with libmagic (for example the one at https://github.com/ahupp/python-magic). A better way, but it's not native Python and is a very extensive library, would be to use PIL http://www.pythonware.com/products/pil/.

Upvotes: 2

Related Questions