code_junkie

Python: Check if uploaded file is jpg

Nov 12th, 2011
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. ...
  2. incomming_image = self.request.get("img")
  3. image = db.Blob(incomming_image)
  4. ...
  5.  
  6. Start Marker | JFIF Marker | Header Length | Identifier
  7. 0xff, 0xd8 | 0xff, 0xe0 | 2-bytes | "JFIF"
  8.  
  9. def is_jpg(filename):
  10. data = open(filename,'rb').read(11)
  11. if data[:4] != 'xffxd8xffxe0': return False
  12. if data[6:] != 'JFIF': return False
  13. return True
  14.  
  15. from PIL import Image
  16. def is_jpg(filename):
  17. try:
  18. i=Image.open(filename)
  19. return i.format =='JPEG'
  20. except IOError:
  21. return False
  22.  
  23. import imghdr
  24.  
  25. image_type = imghdr.what(filename)
  26. if not image_type:
  27. print "error"
  28. else:
  29. print image_type
  30.  
  31. image_type = imghdr.what(filename, incomming_image)
  32.  
  33. ${h.form(h.url_for(action="save_image"), multipart=True)}
  34. Upload file: ${h.file("upload_file")} <br />
  35. ${h.submit("Submit", "Submit")}
  36. ${h.end_form()}
  37.  
  38. def save_image(self):
  39. upload_file = request.POST["upload_file"]
  40. image_type = imghdr.what(upload_file.filename, upload_file.value)
  41. if not image_type:
  42. return "error"
  43. else:
  44. return image_type
  45.  
  46. >>> import Image
  47. >>> im = Image.open("lena.ppm")
  48. >>> print im.format, im.size, im.mode
  49.  
  50. import magic
  51.  
  52. ms = magic.open(magic.MAGIC_NONE)
  53. ms.load()
  54. type = ms.file("/path/to/some/file")
  55. print type
  56.  
  57. f = file("/path/to/some/file", "r")
  58. buffer = f.read(4096)
  59. f.close()
  60.  
  61. type = ms.buffer(buffer)
  62. print type
  63.  
  64. ms.close()
Add Comment
Please, Sign In to add comment