在Python中从Url获​​取图像尺寸 [英] Get Image Dimensions from Url in Python

查看:119
本文介绍了在Python中从Url获​​取图像尺寸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望从网站上的查看器中获取图像尺寸。

I want to get the image dimensions as seen from a viewer on a website.

我正在使用美丽的汤,我得到这样的图像链接:

I'm using beautiful soup and I get image links like this:

links = soup.findAll('img', {"src":True})

我得到图像尺寸的方法是使用:

The way I get the image dimensions is by using:

link.has_key('height')
height = link['height']

和宽度相似。但是,某些链接只具有其中一个属性。我尝试过PIL但是如果下载则会给出实际图像大小。

and similarly with width as well. However, some links only have one of these attributes. I tried PIL but that gives the actual image size if downloaded.

有没有其他方法可以找到网站上看到的图片尺寸?

Is there any other way of finding the image dimensions as seen on a website?

推荐答案

您的主要问题是您正在搜索html源代码以获取高度和宽度的参考。在大多数情况下(当事情做得好),图像没有在html中指定的高度和宽度,在这种情况下,它们在图像文件本身的高度和宽度处呈现。

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

要求:
此方法需要PIL库进行图像处理。

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

# from command line in a virtual environment
pip install PIL

这篇关于在Python中从Url获​​取图像尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆