Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gerrymcdonnell/68663fc4c671354dbdab667709588a71 to your computer and use it in GitHub Desktop.
Save gerrymcdonnell/68663fc4c671354dbdab667709588a71 to your computer and use it in GitHub Desktop.
Python script to detect corrupt Images/jpg Files
__author__ = 'gerry'
#verify if an image is corrupt or not
#help from https://stackoverflow.com/questions/3964681/find-all-files-in-a-directory-with-extension-txt-in-python
img_dir="c://temp//myimages/"
corrupt_img_dir="c://temp//myimages//corruptimages//"
good_img_dir="c://temp//myimages///goodimages//"
from PIL import Image
import os,time
def verify_image(img_file):
#test image
try:
v_image = Image.open(img_file)
v_image.verify()
return True;
#is valid
#print("valid file: "+img_file)
except OSError:
return False;
#main script
for root, dirs, files in os.walk(img_dir):
for file in files:
if file.endswith(".jpg"):
currentFile=os.path.join(root, file)
#test image
if verify_image(currentFile):
new_file_name=good_img_dir+time.strftime("%Y%m%d%H%M%S_"+os.path.basename(currentFile))
print("good file, moving to dir: "+new_file_name)
try:
os.rename(currentFile, new_file_name)
except WindowsError:
print("error moving file")
else:
#Move to corrupt folder
#makefilename unique
#new_file_name=corrupt_img_dir+time.strftime("%Y%m%d%H%M%S_"+os.path.basename(currentFile))
print("corrupt file")
#os.rename(currentFile, new_file_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment