【问题标题】:How can I verify this URL directs to an image?如何验证此 URL 重定向到图像?
【发布时间】:2015-08-13 23:07:32
【问题描述】:

我正在开发一项用 Python 编写的服务,该服务有时会从给定的 URL 下载图像并将它们存储在服务器上。

此服务会检查从 URL 返回的内容类型,并且仅在内容类型为“image/jpeg”等时才下载图像。

我最近遇到了以下 URL 的一个有趣问题: http://www.nationaldentalreviews.org/Handlers/ImageDisplay.ashx?qUID=8597&qType=__ProfileMicroSite

此 URL 在浏览器中打开时会显示某种编码字符串。

当用作图像标签的“src”时,它会渲染图像。

<html>
<body>
  <img src = 'http://www.nationaldentalreviews.org/Handlers/ImageDisplay.ashx?qUID=8597&amp;qType=__ProfileMicroSite'>
</body>
</html>

此 URL 的 content-type 是 text/html

在 Python 中,有什么方法可以让我确定此 URL 指向可用作“src”的图像吗?

【问题讨论】:

  • 你的 Python 版本是多少?

标签: image python-2.7 encoding


【解决方案1】:

使用内置的imghdr 模块:

>>> import imghdr
>>> import urllib2
>>> 
>>> url = 'http://www.nationaldentalreviews.org/Handlers/ImageDisplay.ashx?qUID=8597&qType=__ProfileMicroSite'
>>> data = urllib2.urlopen(url).read()
>>> 
>>> imghdr.what(None, data)
'jpeg'
>>> # To show that it's only checking the header; don't do this though
>>> imghdr.what('', data:10])
'jpeg'
>>> imghdr.what('', 'CORRUPT_OR_NOT_AN_IMAGE' + data)
>>> # The last call returns None
>>> 

【讨论】:

  • -5的意义是什么?
  • 为什么投反对票?我很高兴有机会解决任何问题:)。
【解决方案2】:

检索图像数据并使用https://docs.python.org/2/library/imghdr.html

【讨论】:

    【解决方案3】:

    您看到的编码字符串是 jpeg 的二进制内容。服务器将内容类型标头错误地设置为 text/html,因此您的浏览器试图将其显示为 html 而不是 jpeg。

    您可以下载文件并使用python图像库尝试打开图像,如果不是图像,PIL会抛出异常。

    >>> from PIL import Image
    >>> im = Image.open("foo.jpg")
    >>> im
    <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=229x103 at 0x21A3300>
    >>> im = Image.open("html.jpg")
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "c:\python27\lib\site-packages\PIL\Image.py", line 1980, in open
        raise IOError("cannot identify image file")
    IOError: cannot identify image file
    >>>
    

    【讨论】:

      猜你喜欢
      • 2011-10-28
      • 1970-01-01
      • 2019-11-14
      • 1970-01-01
      • 2012-03-02
      • 2017-05-14
      • 2017-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多