Python App Engine loads image content

I know that I can accept image uploads in the form of a POST for App Engine, for example:

<form action="/upload_received" enctype="multipart/form-data" method="post"> <div><input type="file" name="img"/></div> <div><input type="submit" value="Upload Image"></div> </form> 

Then in Python code I can do something like

 image = self.request.get("img") 

But how can I figure out what the content type of this image should be when it is later shown to the user? It seems the most reliable way is to figure it out from the image data itself, but how to get it easy? I did not see anything suitable in the google.appengine.api image package.

Should I just look for the magic image headers in my own code, or is there some kind of method already?

Edit:

Here, the simplified solution that I ended up using seems to work well enough for my purposes and eliminates the need to save the image type as a separate field in the data warehouse:

 # Given an image, returns the mime type or None if could not detect. def detect_mime_from_image_data(self, image): if image[1:4] == 'PNG': return 'image/png' if image[0:3] == 'GIF': return 'image/gif' if image[6:10] == 'JFIF': return 'image/jpeg' return None 
+4
source share
3 answers

Instead of using self.request.get (field name), use self.request.POST [file_name]. This returns a cgi.FieldStorage object (see Python library docs for details) that has the attributes "file name", "type" and "value".

+5
source

Try the python mimetypes module, it will guess the content type and encoding for you,

eg.

β†’ import mimetypes

<P β†’> mimetypes.guess_type ("/ home / Sean / desktop / comedy / 30seconds.mp4")

('video / mp4', None)

+2
source

Based on my research, browsers, with the exception of Internet Explorer (at least 6), determine the mime file type using the file extension. Given that you need mime image types, you can use a simple Python dictionary to achieve this.

Unfortunately, I do not know any method in Python that tries to guess the type of image by reading some magic bytes (the fileinfo method does in PHP). Perhaps you can apply the EAFP principle (easier to ask for forgiveness than permission) with the appengine API.

Yes, it looks like the image API is not telling you the type of image you uploaded. In this case, I have to create this Python dictionary to map file extensions to the mime image type, and then try to load the image, expecting a NotImageError() exception. If all goes well, then I assume the mime type was fine.

0
source

All Articles