Python Image Library (PIL) Tutorial: Splitting an Image into Multiple Tiles
This tutorial demonstrates how to use Python's Pillow library to divide a rectangular image into nine equal tiles by calculating optimal dimensions, cropping each region, and saving the resulting pieces, providing a concise, code‑first approach for image manipulation tasks.
This article introduces a simple Python project that uses the Pillow (PIL) library to transform a single rectangular image into nine separate tiles. The goal is to replace a large picture with multiple smaller, equally sized images that together form the original layout.
The core idea is straightforward: compute the width and height of each tile based on the original image dimensions, then iteratively crop the image into a 3×3 grid. The largest dimension (width or height) is chosen as the reference, and the other dimension is adjusted proportionally.
Below is a representative code snippet that defines the splitting logic and saves each tile as a separate PNG file:
# Define a function to split an image into tiles
from PIL import Image
def split_image(image_path, rows=3, cols=3):
img = Image.open(image_path)
w, h = img.size
tile_w = w // cols
tile_h = h // rows
tiles = []
for i in range(rows):
for j in range(cols):
left = j * tile_w
upper = i * tile_h
right = left + tile_w
lower = upper + tile_h
tile = img.crop((left, upper, right, lower))
tiles.append(tile)
return tiles
# Save the tiles
tiles = split_image('original.jpg')
for idx, tile in enumerate(tiles):
tile.save(f'./result/tile_{idx}.png')The script first opens the source image, calculates each tile's width and height, and then uses nested loops to crop the image at the appropriate coordinates. Each cropped piece is stored in a list and subsequently written to disk with a sequential filename.
By adjusting the rows and cols parameters, the same routine can be adapted to generate any grid size, making it a flexible foundation for more complex image‑processing pipelines.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.