Python: Download image file from URL and retrieve common properties

With the following snippets, you can get yourself:

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

So, the code snippet!

from PIL import Image
import urllib2
import cStringIO
import os
from stat import ST_SIZE


file = cStringIO.StringIO(urllib2.urlopen(image_url).read())
filename = "/tmp/file_%s.jpg" % datetime.datetime.now().strftime("%s")

image_info = Image.open(file)
image_info.save(filename)
file.close()

file_info = os.stat(filename)

filemime = "image/%s" % image_info.format.lower() # JPEG, PNG, GIF
width, height = image_info.size
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.

os.remove(filename)

Sources

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