Create a 3×3 Avatar Grid and Merge with a Flag to Generate a GIF Using Python Pillow
This guide shows how to split an avatar image into nine equal parts with Pillow, overlay each part onto a resized flag background, and combine the frames into an animated GIF, including full Python code and installation instructions.
Overview
This article demonstrates how to use the Python Pillow library to divide an avatar picture into a 3×3 grid, blend each cell with a flag image, and assemble the results into an animated GIF.
Splitting the Avatar
from PIL import Image, ImageSequence
def split_image(image_path):
# Open the avatar image
image = Image.open(image_path)
# Get image dimensions
width, height = image.size
# Compute size of each grid cell
grid_width = width // 3
grid_height = height // 3
# Crop the avatar into nine cells
grid_images = []
for i in range(3):
for j in range(3):
left = j * grid_width
upper = i * grid_height
right = left + grid_width
lower = upper + grid_height
grid_image = image.crop((left, upper, right, lower))
grid_images.append(grid_image)
return grid_imagesMerging with the Flag Background
def merge_with_flag(grid_images, flag_image_path, output_path):
# Open the flag background image
flag_image = Image.open(flag_image_path)
# Resize the flag to match each grid cell
resized_flag_image = flag_image.resize((grid_images[0].width, grid_images[0].height))
# Create a list to hold merged frames
merged_images = []
for grid_image in grid_images:
merged_image = Image.new("RGB", (grid_image.width, grid_image.height))
merged_image.paste(grid_image, (0, 0))
# Paste the flag using its alpha channel as mask
merged_image.paste(resized_flag_image, (0, 0), mask=resized_flag_image)
merged_images.append(merged_image)
# Save the sequence as an animated GIF
merged_images[0].save(output_path, save_all=True, append_images=merged_images[1:], loop=0, duration=200)Running the Script
if __name__ == "__main__":
# Paths to your files
image_path = "avatar.jpg"
flag_image_path = "flag.jpg"
output_path = "merged_image.gif"
# Split the avatar
grid_images = split_image(image_path)
# Merge each cell with the flag and create the GIF
merge_with_flag(grid_images, flag_image_path, output_path)Installation
Make sure Pillow is installed before running the script:
pip install pillowResult
The script produces merged_image.gif, an animated GIF where each of the nine avatar sections is overlaid on the flag background.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
