1.以下代码可以应付常见的大部分情形
def badImgFast(fn,imgType):
if os.path.getsize(fn) < 512:
return True
valid=False
with open(fn, "rb") as f:
f.seek(-2, 2)
buf = f.read()
valid=buf.endswith(b'\xff\xd9') or buf.endswith(b'\xae\x82') or \
buf.endswith(b'\x00\x3B') or buf.endswith(b'\x60\x82') #检测jpg图片完整性, 检测png图片完整性
buf.endswith(b'\x00\x00')
return valid or (imghdr.what(nm) =="webp")
2.一种可靠的实现
def converttowebp(fn):
if imghdr.what(fn)!=None:
desnm="d:/webpImg/{}.webp".format(os.path.splitext(fn)[0].split('/')[-1])
with Image.open(fn) as im:
try:
im.save(desnm, "WEBP")
webpn += 1
except Exception:
pass
#os.remove(fn)
|