Get Image Dimensions from Url in Python

岁酱吖の 提交于 2019-12-04 16:51:59
Tom Rose

Your main issue is you are searching the html source for references to height and width. In most cases (when things are done well), images don't have height and width specified in html, in which case they are rendered at the height and width of the image file itself.

To get the height and width of the image file, you need to actually query for and load that file, then check the height and width using image processing. If this is what you want, let me know, and I'll help you work through that process.

import urllib, cStringIO
from PIL import Image

# given an object called 'link'

SITE_URL = "http://www.targetsite.com"
URL = SITE_URL + link['src']
# Here's a sample url that works for demo purposes
# URL = "http://therealtomrose.therealrosefamily.com/wp-content/uploads/2012/08/headshot_tight.png"
file = cStringIO.StringIO(urllib.urlopen(URL).read())
im=Image.open(file)
width, height = im.size
if link.has_key('height'):
    height = link['height']  # set height if site modifies it
if link.has_key('width'):
    width = link['width']  # set width if site modifies it

Requirements: This method requires the PIL library for image processing.

# from command line in a virtual environment
pip install PIL
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!