Reputation: 272094
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)
When I do this, there is an error:
print StringIO(f)
File "/usr/lib/python2.6/dist-packages/PIL/Image.py", line 1980, in open
raise IOError("cannot identify image file")
IOError: cannot identify image file
Upvotes: 0
Views: 553
Reputation: 118498
The problem is that your Accept-Encoding
states gzip
so you're probably getting a gzipped image.
I just tried your code with your gzip decompression on and it works without any problems.
pic = download("http://media2.ct.yelpcdn.com/photo/2MdauidaMUazuew2h0pdgQ/l", g=True)
s = getSize(pic)
So does changing your 'Accept-Encoding'
from 'gzip'
to 'image.*'
ree.add_header('User-Agent',random.choice(agents))
ree.add_header('Accept-Encoding', 'image.*')
Part 2:
You could always ask for gzip
and wrap with try/except here to return the data unaltered if gzip complains.
try:
compressedstream = StringIO(h)
gzipper = gzip.GzipFile(fileobj=compressedstream)
data = gzipper.read()
return data
except IOError: # not gzip
return h
Upvotes: 3