When working with images in Python, it’s crucial to ensure the integrity and validity of the files being processed. Invalid or corrupted image files can lead to unexpected errors and disruptions in your applications. In this article, we will explore different methods to check if a file is a valid image using Python.
Check If A File is a Valid Image with Python
Below, are the methods of Check If A File is a Valid Image with Python:
- Using Pillow (PIL) Library
- Using imghdr Module
- Using file extensions
Check If A File Is A Valid Image Using Pillow(PIL) Library
In this example, code defines a function `is_valid_image_pillow` that checks if an image file is valid using the Pillow (PIL) library. It then iterates through a list of file names, prints the file name, and checks and prints whether each file is a valid image using the defined function. The file paths are constructed using the given directory path and file names.
import os
from PIL import Image
# Directory path directory_path = r "C:\Users\shrav\Desktop\GFG"
# File names file_names = [ "GFG.txt" , "GFG.jpg" ]
# Get full file paths file_paths = [os.path.join(directory_path, file_name)
for file_name in file_names]
# 1. Using Pillow (PIL) def is_valid_image_pillow(file_name):
try :
with Image. open (file_name) as img:
img.verify()
return True
except (IOError, SyntaxError):
return False
# Example usage for file_name in file_names:
print (f "File: {file_name}" )
if os.path.exists(file_name): # Check if the file exists
print ( "Using Pillow (PIL):" , is_valid_image_pillow(file_name))
print ()
else :
print (f "File '{file_name}' not found." )
print ()
|
Output:
File: GFG.txt
Using Pillow (PIL): False
File: GFG.jpg
Using Pillow (PIL): True
Check If A File Is A Valid Image Using imghdr Module
In this example, below code defines a function is_valid_image_imghdr
that checks if an image file is valid using the imghdr
module. It iterates through a list of file names, prints the file name, and checks and prints whether each file is a valid image using the defined function. The file paths are constructed using the given directory path and file names
import os
import imghdr
# Directory path directory_path = r "C:\Users\shrav\Desktop\GFG"
# File names file_names = [ "GFG.txt" , "GFG.jpg" ]
# Get full file paths file_paths = [os.path.join(directory_path, file_name)
for file_name in file_names]
# 2. Using imghdr def is_valid_image_imghdr(file_name):
with open (file_name, 'rb' ) as f:
header = f.read( 32 ) # Read the first 32 bytes
return imghdr.what( None , header) is not None
# Example usage for file_name in file_names:
print (f "File: {file_name}" )
if os.path.exists(file_name): # Check if the file exists
print ( "Using imghdr:" , is_valid_image_imghdr(file_name))
print ()
else :
print (f "File '{file_name}' not found." )
print ()
|
Output:
Warning (from warnings module):
File "C:\Users\shrav\Desktop\GFG\GFG.py", line 2
import imghdr
DeprecationWarning: 'imghdr' is deprecated and slated for removal in Python 3.13
File: GFG.txt
Using imghdr: False
File: GFG.jpg
Using imghdr: True
Check If A File Is A Valid Image Using File Extension
In this example, below code defines a function is_valid_image_extension
to check if files with given names in a specified directory are valid images based on their file extensions. It iterates through a list of file names, prints the file name, and checks and prints whether each file is a valid image using the defined function.
import os
# Directory path directory_path = r "C:\Users\shrav\Desktop\GFG"
# File names file_names = [ "GFG.txt" , "GFG.jpg" ]
# Get full file paths file_paths = [os.path.join(directory_path, file_name)
for file_name in file_names]
# 4. Using file extension def is_valid_image_extension(file_name):
valid_extensions = { '.jpg' , '.jpeg' , '.png' , '.gif' , '.bmp' }
return any (file_name.lower().endswith(ext) for ext in valid_extensions)
# Example for file_name in file_names:
print (f "File: {file_name}" )
if os.path.exists(file_name): # Check if the file exists
print ( "Using file extension:" , is_valid_image_extension(file_name))
print ()
else :
print (f "File '{file_name}' not found." )
print ()
|
Output:
File: GFG.txt
Using file extension: False
File: GFG.jpg
Using file extension: True