In this Python tutorial, we will learn how to read the file size and type of an image. This is useful for validating image files before processing them, ensuring they meet specific requirements (e.g., size limits for uploads). We will use the os
module to get the file size and the PIL
(Pillow) library to determine the image type.
import os
from PIL import Image
# Function to get image file size and type
def get_image_info(image_path):
try:
# Get file size in bytes
file_size = os.path.getsize(image_path) # Size in bytes
# Open the image using PIL to get file type
with Image.open(image_path) as img:
image_type = img.format # Get image format (e.g., JPEG, PNG)
# Convert size to KB
file_size_kb = file_size / 1024
print(f"Image: {image_path}")
print(f"File Type: {image_type}")
print(f"File Size: {file_size_kb:.2f} KB")
except FileNotFoundError:
print(f"Error: The file '{image_path}' does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
# Specify the image file path
image_file = "example.jpg"
# Get image information
get_image_info(image_file)
Assume example.jpg
is a JPEG image with a file size of 205 KB, the output will be:
Image: example.jpg
File Type: JPEG
File Size: 205.00 KB
If the file does not exist, the output will be:
Error: The file 'example.jpg' does not exist.
os.path.getsize()
to Get File Size:
os.path.getsize(image_path)
returns the file size in bytes.1024
.PIL.Image.open()
to Get Image Type:
Image.open(image_path)
..format
attribute of the image object gives the image type (e.g., JPEG, PNG).FileNotFoundError
is caught if the specified file does not exist.Exception as e
ensures any other errors (e.g., unsupported image format) are handled gracefully.This approach helps in verifying image files before further processing, making it useful for applications like file uploads or automated image management systems.