Check If A File is Valid Image with Python
Last Updated :
28 Apr, 2025
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:
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.
Python3
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
Python3
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.
Python3
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
Similar Reads
Check If A File is Writable in Python When it comes to Python programming it is essential to work with files. One important aspect is making sure that a file can be written before you try to make any changes. In this article, we will see how we can check if a file is writable in Python. Check If a File Is Writable in PythonBelow are som
3 min read
Check If File is Readable in Python We are given a file and we have to check whether the file is readable in Python or not. In this article, we will see how we can check if a file is readable or not by using different approaches in Python. How to Check if a File is Readable in PythonBelow, are the methods of How to Check If a File Is
3 min read
Check If a Text File Empty in Python Before performing any operations on your required file, you may need to check whether a file is empty or has any data inside it. An empty file is one that contains no data and has a size of zero bytes. In this article, we will look at how to check whether a text file is empty using Python.Check if a
4 min read
Check if a File Exists in Python When working with files in Python, we often need to check if a file exists before performing any operations like reading or writing. by using some simple methods we can check if a file exists in Python without tackling any error. Using pathlib.Path.exists (Recommended Method)Starting with Python 3.4
3 min read
Check a File is Opened or Closed in Python In computer programming, working with files is something we often do. Python, a programming language, gives us useful tools to handle files. One important thing to know when dealing with files is whether a file is currently open or closed. This is crucial to avoid problems and make sure the data sta
4 min read
Check end of file in Python In Python, checking the end of a file is easy and can be done using different methods. One of the simplest ways to check the end of a file is by reading the file's content in chunks. When read() method reaches the end, it returns an empty string.Pythonf = open("file.txt", "r") # Read the entire cont
2 min read