面对Python中似乎是一个流行的模块/函数(getimageinfo.py)的错误。想要获得图像大小而不下载它们。但是,遇到以下错误:
>>> import getimageinfo
>>> import urllib2
>>> imgdata = urllib2.urlopen('https://cdn.programiz.com/sites/tutorial2program/files/python-modules.jpg')
>>> image_type,width,height = getimageinfo.getImageInfo(imgdata)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "getimageinfo.py", line 61, in getImageInfo
width = int(w)
UnboundLocalError: local variable 'w' referenced before assignment
>>>
错误似乎来自代码的这一部分:
# handle JPEGs
elif (size >= 2) and data.startswith('\377\330'):
content_type = 'image/jpeg'
jpeg = StringIO.StringIO(data)
jpeg.read(2)
b = jpeg.read(1)
try:
while (b and ord(b) != 0xDA):
while (ord(b) != 0xFF): b = jpeg.read(1)
while (ord(b) == 0xFF): b = jpeg.read(1)
if (ord(b) >= 0xC0 and ord(b) <= 0xC3):
jpeg.read(3)
h, w = struct.unpack(">HH", jpeg.read(4))
break
else:
jpeg.read(int(struct.unpack(">H", jpeg.read(2))[0])-2)
b = jpeg.read(1)
width = int(w)
height = int(h)
except struct.error:
pass
except ValueError:
pass
似乎没有其他人面临该模块的错误(至少没有人报告过Stackoverflow或其他论坛)。我如何解决它?我想得到
h, w = struct.unpack(">HH", jpeg.read(4))
以外的行如果&#39;声明,但不知道在图像具有奇怪属性的情况下它会有多严重。 (新编码)
答案 0 :(得分:0)
如果条件w
为(ord(b) >= 0xC0 and ord(b) <= 0xC3)
,您尚未声明False
的默认值,我可以添加两条注释行
while (b and ord(b) != 0xDA):
while (ord(b) != 0xFF): b = jpeg.read(1)
while (ord(b) == 0xFF): b = jpeg.read(1)
# HERE YOU NEED SET VALUE for w and h
if (ord(b) >= 0xC0 and ord(b) <= 0xC3):
jpeg.read(3)
h, w = struct.unpack(">HH", jpeg.read(4))
break
else:
# Or HERE YOU NEED SET VALUE for w and h
jpeg.read(int(struct.unpack(">H", jpeg.read(2))[0])-2)
b = jpeg.read(1)
width = int(w)
height = int(h)