Python Fileoperations: Read the File Size and Type of an Image

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.


Code Example:

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)

Output (Example Scenario):

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.

Code Explanation:

  1. Using os.path.getsize() to Get File Size:
    • os.path.getsize(image_path) returns the file size in bytes.
    • We convert it to kilobytes (KB) by dividing by 1024.
  2. Using PIL.Image.open() to Get Image Type:
    • We open the image file using Image.open(image_path).
    • The .format attribute of the image object gives the image type (e.g., JPEG, PNG).
  3. Error Handling:
    • A FileNotFoundError is caught if the specified file does not exist.
    • A general exception 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.