【问题标题】:Python, IOError: cannot identify image filePython,IOError:无法识别图像文件
【发布时间】:2015-08-24 07:55:02
【问题描述】:

我知道有很多类似的问题,但我认为,没有一个igual(我认为)。我有一组图片的网址,我想下载它。但是当我尝试保存图像时,我得到了这个错误。我不知道如何使它工作。

这是我的代码:

listOfImagesUrl = ['https://cdn.psychologytoday.com/sites/default/files/blogs/1023/2012/09/105928-103553.jpg', 'http://i.livescience.com/images/i/000/048/264/original/disgusted-101130-02.jpg%3F1324346664', 'http://barfblog.com/wp-content/uploads/images/disgust.story.jpg', 'http://cache1.asset-cache.net/gc/148190074-people-making-disgusted-faces-gettyimages.jpg%3Fv%3D1%26c%3DIWSAsset%26k%3D2%26d%3Dww%252BvNwEe%252BXzLnQze1Z2w9KNDivKR%252BEqGJ2cPfDe1oeinIezLX%252B8y1tIG3LNjTbL5']

imageNumber = 1

for imageUrl in listOfImagesUrl:

    file = cStringIO.StringIO(urllib.urlopen(imageUrl).read())
    img = Image.open(file)
    img.save("/tmp/test/" + str(imageNumber) + "." + img.format)
    print "DONE: " + str(imageNumber) + " of " + str(len(listOfImagesUrl))
    imageNumber += 1

我使用 sleeplessnerd 对 this stackoverflow 问题的回答解决了 url 问题。问题是我必须在 urllib2 上启用 cookie。

【问题讨论】:

  • 第二个 URL 在使用 urllib 加载并且响应正文为空时会给您一个 500 错误。在尝试读取数据之前,请检查您的回复。
  • %3F 序列是一个编码的问号。它不应该是 URL 路径的一部分,您有一个查询参数(可能是缓存破坏器),而是编码到 URL 中。最后一个网址也一样。
  • 但是,如果我将我的第二个网址改为livescience.com/images/i/000/048/264/original/…,它仍然无法正常工作。怎么了?感谢您的帮助。
  • urllib.urlopen documentation 的末尾说“自 2.6 版起已弃用:urlopen() 函数已在 Python 3 中删除,取而代之的是 urllib2.urlopen()。”
  • 谢谢,我改成 urllib2 又得到一个新的错误。 urllib2.HTTPError:HTTP 错误 301:HTTP 服务器返回一个重定向错误,这将导致无限循环。最后 30x 错误消息是:已永久移动。我现在将搜索此错误的修复程序。

标签: python python-2.7 image-processing python-imaging-library


【解决方案1】:

我切换到urllib2 并重组了您的代码,如图所示以提供更多错误信息。看来你的大部分图片网址都不好。

from urllib2 import urlopen, URLError
from cStringIO import StringIO
from PIL import Image

listOfImagesUrl = [
    'http://barfblog.com/wp-content/uploads/images/disgust.story.jpg',
    'https://cdn.psychologytoday.com/sites/default/files/blogs/1023/2012/09/105928-103553.jpg',
    'http://i.livescience.com/images/i/000/048/264/original/disgusted-101130-02.jpg%3F1324346664',
    'http://cache1.asset-cache.net/gc/148190074-people-making-disgusted-faces-gettyimages.jpg%3Fv%3D1%26c%3DIWSAsset%26k%3D2%26d%3Dww%252BvNwEe%252BXzLnQze1Z2w9KNDivKR%252BEqGJ2cPfDe1oeinIezLX%252B8y1tIG3LNjTbL5'
]

for imageNumber, imageUrl in enumerate(listOfImagesUrl, start=1):
    try:
        url = urlopen(imageUrl)
    except URLError as e:
        print "skipping {}".format(imageUrl)
        print "  error: {}".format(e)
        continue
    file = StringIO(url.read())
    img = Image.open(file)
    img.save("/tmp/test/" + str(imageNumber) + "." + img.format)
    print "DONE: " + str(imageNumber) + " of " + str(len(listOfImagesUrl))

【讨论】:

  • 谢谢你,martineau,你的代码比我的好多了。我不明白的一件事是为什么我会收到这些错误?如果我在浏览器上打开网址,它会显示一张图片。发生了什么?
  • @Caaarlos:感谢您接受我的回答,尽管我不知道需要启用 cookie 才能使 url 正常工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-02
  • 1970-01-01
  • 2013-10-14
  • 1970-01-01
  • 2020-12-17
  • 2020-05-26
相关资源
最近更新 更多