Loading and displaying an image using the Pillow library

In this program, we will read or load an image using the Pillow library. The Pillow library provides the Image.open() method that takes the file path or filename as a string parameter. To display the image, we use the show() function which opens the image in the default image viewer.

Installing Pillow

First, install the Pillow library if you haven't already ?

pip install Pillow

Basic Image Loading and Display

Here's how to load and display an image using Pillow ?

from PIL import Image
import io
import base64

# Create a simple test image (since we can't load external files)
# This creates a 200x200 red square
img = Image.new('RGB', (200, 200), color='red')

# Display basic image information
print(f"Image size: {img.size}")
print(f"Image mode: {img.mode}")
print(f"Image format: {img.format}")
Image size: (200, 200)
Image mode: RGB
Image format: None

Loading an Image from File

To load an actual image file from your system ?

from PIL import Image

# Load an image from file
image = Image.open('path/to/your/image.jpg')

# Display the image
image.show()

# Get image properties
print(f"Size: {image.size}")
print(f"Mode: {image.mode}")
print(f"Format: {image.format}")

Working with Different Image Formats

Pillow supports various image formats including JPEG, PNG, BMP, and GIF ?

from PIL import Image

# Create images in different formats
formats = ['JPEG', 'PNG', 'BMP']

for fmt in formats:
    # Create a sample image
    img = Image.new('RGB', (100, 100), color='blue')
    print(f"Created {fmt} compatible image")
    print(f"Size: {img.size}, Mode: {img.mode}")
Created JPEG compatible image
Size: (100, 100), Mode: RGB
Created PNG compatible image
Size: (100, 100), Mode: RGB
Created BMP compatible image
Size: (100, 100), Mode: RGB

Error Handling

Always handle potential errors when loading images ?

from PIL import Image

try:
    image = Image.open('image.jpg')
    image.show()
    print("Image loaded successfully!")
except FileNotFoundError:
    print("Error: Image file not found")
except Exception as e:
    print(f"Error loading image: {e}")

Key Methods

Method Purpose Parameters
Image.open() Load image from file File path (string)
show() Display image None
save() Save image to file File path, format (optional)

Conclusion

The Pillow library makes loading and displaying images simple with Image.open() and show() methods. Always include error handling when working with external image files to make your code more robust.

Updated on: 2026-03-25T18:06:38+05:30

268 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements