簡體   English   中英

Python PIL:IOError:無法識別圖像文件

[英]Python PIL: IOError: cannot identify image file

我想從以下網址獲取圖片:

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:無法識別圖像文件

我用這種方式復制了數百張圖片,所以我不確定這里有什么特別之處。 我能得到這張照片嗎?

當我打開文件時使用

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

問題不存在於圖像中。

>>> 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'

使用用戶代理標頭將解決問題。

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)

要獲得一些圖像,您可以先保存圖像,然后將其加載到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)
...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM