def getSize(f):
print StringIO(f)
im = Image.open(StringIO(f))
size = im.size[0], im.size[1]
return size
def download(source_url, g = False, correct_url = True):
try:
socket.setdefaulttimeout(10)
agents = ['Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)','Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1)','Microsoft Internet Explorer/4.0b1 (Windows 95)','Opera/8.00 (Windows NT 5.1; U; en)']
ree = urllib2.Request(source_url)
ree.add_header('User-Agent',random.choice(agents))
ree.add_header('Accept-encoding', 'gzip')
opener = urllib2.build_opener()
h = opener.open(ree).read()
if g:
compressedstream = StringIO(h)
gzipper = gzip.GzipFile(fileobj=compressedstream)
data = gzipper.read()
return data
else:
return h
except Exception, e:
return ""
pic = download("http://media2.ct.yelpcdn.com/photo/2MdauidaMUazuew2h0pdgQ/l")
s = getSize(pic)
当我这样做时,有一个错误:
^{pr2}$
问题是您的
Accept-Encoding
状态为gzip
,所以您可能得到了一个gzip图像。在我刚刚在gzip解压的情况下尝试了你的代码,它工作起来没有任何问题。在
把你的
^{pr2}$'Accept-Encoding'
从'gzip'
改为'image.*'
第2部分:
如果gzip抱怨,您可以始终请求
gzip
并用try/except在此处返回未更改的数据。在相关问题 更多 >
编程相关推荐