python检测图片是否正确(异常提示)
利用OpenCV来改变图片的大小,如果不能改变,有可能是因为图片下载得不完整。比较简陋,但是好像也管用。
# -*- coding: utf-8 -*- import io import traceback import time import cv2 import os def TestImg(savePath): exMsg = '' try: start = time.clock() img = cv2.imread(savePath) cv2.resize(img, (100, 100), interpolation=cv2.INTER_NEAREST) end = time.clock() print(end -start) except: exMsg = '* %s' % traceback.format_exc() print(exMsg) if exMsg: return False return True import requests try: savePath='test.jpg' r=requests.get('http://xxx.com/xxx.jpg',timeout=30) r.raise_for_status() # 如果响应状态码不是 200,就主动抛出异常 if(r.text!=''): with open(savePath,'wb')as f: f.write(r.content) f.close() if TestImg(savePath): print('图片正确') else: os.remove(savePath) print('图片错误') else: print('图片为空') except requests.RequestException as e: print(e)