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!

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

Related Posts

0 comments:

Post a Comment

Leave your thoughts ...
---
If you are having trouble with copy/pasting in comments, you need to sign in or click 'Preview'. For more information about this Firefox bug, see here.

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