Python PIL:IOError:无法识别图像文件

时间:2013-06-18 20:53:56

标签: python python-imaging-library

我正在尝试从以下网址获取图片:

image_url = http://www.eatwell101.com/wp-content/uploads/2012/11/Potato-Pancakes-recipe.jpg?b14316

当我在浏览器中导航到它时,它确实看起来像一个图像。但是当我尝试时出现错误:

import urllib, cStringIO, PIL
from PIL import Image

img_file = cStringIO.StringIO(urllib.urlopen(image_url).read())   
image = Image.open(img_file)
  

IOError:无法识别图像文件

我已经用这种方式复制了数百张图片,所以我不确定这里有什么特别之处。我能得到这张照片吗?

3 个答案:

答案 0 :(得分:4)

当我使用

打开文件时
In [3]: f = urllib.urlopen('http://www.eatwell101.com/wp-content/uploads/2012/11/Potato-Pancakes-recipe.jpg')

In [9]: f.code
Out[9]: 403

这不会返回图像。

您可以尝试指定用户代理标头,看看是否可以诱骗服务器认为您是浏览器。

使用requests库(因为它更容易发送标题信息)

In [7]: f = requests.get('http://www.eatwell101.com/wp-content/uploads/2012/11/Potato-Pancakes-recipe.jpg', headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:16.0) Gecko/20100101 Firefox/16.0,gzip(gfe)'})
In [8]: f.status_code
Out[8]: 200

答案 1 :(得分:3)

问题不存在于图像中。

>>> urllib.urlopen(image_url).read()
'\n<?xml version="1.0" encoding="utf-8"?>\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\n "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n<html>\n  <head>\n    <title>403 You are banned from this site.  Please contact via a different client configuration if you believe that this is a mistake.</title>\n  </head>\n  <body>\n    <h1>Error 403 You are banned from this site.  Please contact via a different client configuration if you believe that this is a mistake.</h1>\n    <p>You are banned from this site.  Please contact via a different client configuration if you believe that this is a mistake.</p>\n    <h3>Guru Meditation:</h3>\n    <p>XID: 1806024796</p>\n    <hr>\n    <p>Varnish cache server</p>\n  </body>\n</html>\n'

使用user agent header将解决问题。

opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
response = opener.open(image_url)
img_file = cStringIO.StringIO(response.read())   
image = Image.open(img_file)

答案 2 :(得分:2)

要获取某些图像,您可以先保存图像,然后将其加载到PIL。例如:

import urllib2,PIL

opener = urllib2.build_opener(urllib2.HTTPRedirectHandler(), urllib2.HTTPCookieProcessor())
image_content = opener.open("http://www.eatwell101.com/wp-content/uploads/2012/11/Potato-Pancakes-recipe.jpg?b14316").read()
opener.close()

save_dir = r"/some/folder/to/save/image.jpg"
f = open(save_dir,'wb')
f.write(image_content)
f.close()

image = Image.open(save_dir)
...