Last modified: Apr 21, 2025 By Alexander Williams
Python Simple Image Gallery Guide
Creating an image gallery in Python is easy. This guide shows you how. Use libraries like PIL and OpenCV. Follow these steps.
Why Create an Image Gallery in Python?
Python is great for image processing. You can automate tasks. Build web apps. Or just organize photos. A gallery helps.
For more on image basics, see our Python Image Analysis Guide.
Required Libraries
You need two main libraries. Pillow (PIL) for basic operations. OpenCV for advanced features.
Install them with pip:
pip install pillow opencv-python
Loading Images
First, load images from a folder. Use os.listdir()
to get files. Then open them with PIL.
from PIL import Image
import os
def load_images(folder):
images = []
for file in os.listdir(folder):
if file.endswith(('jpg', 'png')):
img = Image.open(os.path.join(folder, file))
images.append(img)
return images
Displaying Images
To show images, use Image.show()
. Or create a grid with matplotlib.
import matplotlib.pyplot as plt
def show_gallery(images, cols=3):
fig, axes = plt.subplots(nrows=1, ncols=cols, figsize=(15,5))
for img, ax in zip(images, axes):
ax.imshow(img)
ax.axis('off')
plt.show()
Resizing Images
Make images uniform with Image.resize()
. This helps in grids.
See our Python Image Rescaling Guide for details.
def resize_images(images, size=(200,200)):
return [img.resize(size) for img in images]
Saving the Gallery
Combine images into one file. Use PIL's Image.new()
and Image.paste()
.
def save_gallery(images, output_file, cols=3):
width, height = images[0].size
rows = len(images) // cols
gallery = Image.new('RGB', (cols*width, rows*height))
for i, img in enumerate(images):
gallery.paste(img, (i%cols*width, i//cols*height))
gallery.save(output_file)
Advanced Options
Add borders. Or captions. OpenCV offers more control.
For creative layouts, check our Python Image Collages Guide.
Full Example Code
Here's complete code to create a gallery:
from PIL import Image
import os
import matplotlib.pyplot as plt
# Load and process images
images = load_images('photos')
images = resize_images(images)
# Display
show_gallery(images[:6]) # Show first 6
# Save
save_gallery(images, 'gallery.jpg')
Conclusion
Python makes image galleries simple. Use PIL for basics. OpenCV for advanced features. Automate your photo organization today.
For more image tricks, explore our Python image guides. Start with the Python Image Cropping Guide.