Python: Download image file from URL and retrieve common properties

0 Comments

With the following snippets, you can get yourself:

  • Image width/height
  • Image mime type
  • File size

So, the code snippet!

01.from PIL import Image
02.import urllib2
03.import cStringIO
04.import os
05.from stat import ST_SIZE
06. 
07. 
08.file = cStringIO.StringIO(urllib2.urlopen(image_url).read())
09.filename = "/tmp/file_%s.jpg" % datetime.datetime.now().strftime("%s")
10. 
11.image_info = Image.open(file)
12.image_info.save(filename)
13.file.close()
14. 
15.file_info = os.stat(filename)
16. 
17.filemime = "image/%s" % image_info.format.lower() # JPEG, PNG, GIF
18.width, height = image_info.size
19.filesize = file_info[ST_SIZE]

From Doug Hellmann's blog:

The cStringIO version is written in C for speed, while StringIO is written in Python for portability.

Once you're done, remember to delete the temporary file.

1.os.remove(filename)

Sources

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog