媒体文件是否有效,可以通过获取该媒体文件的媒体属性来判断。
以python语言为例
检查图片是否损坏
使用了cv2和numpy两个模块,获取它的尺寸及通道数,捕获异常,判断损坏
flag=0#标志位 1代表损坏
file='文件路径'
try:#使用cv2.imread(file)路径不能包含中文路径,因此使用下面这种方法
img = cv2.imdecode(np.fromfile(file, dtype=np.uint8), -1)
x, y, c = img.shape
except AttributeError:
print('AttributeError')#图片为0字节发生此错误
flag=1
except cv2.error:
print('cv2.error')#图片损坏
flag=1
except ValueError:#使用cv2.imdecode会发生此错误
pass
except Exception as e:
print(e.__cause__,e.__class__)
if flag==1:对异常文件进行处理
print(file)
infoToDelete += fileName.split('.')[0] + ","
d = os.path.dirname(__file__)
检查视频文件
使用cv2模块获取fps,fps为0,即损坏
cap = cv2.VideoCapture(file)
fps = cap.get(5)
cap.release()
if(fps==0.0):
infoToDelete+=fileName.split('.')[0]+","
os.remove(file)
print("error:",file)