Generating GIF Animations and Performing Image Manipulation with Python Pillow
This tutorial explains how to install Pillow, create GIF animations, and perform common image processing tasks such as resizing, cropping, adding watermarks, rotating, and applying filter effects using Python code examples.
To create GIF animations with Python, first install the Pillow library using pip install pillow .
Then use the following script to create a new GIF, open image frames, paste them, set frame duration, and save the animation:
from PIL import Image
# Create a new GIF object
gif = Image.new('RGB', (200, 200), color='white')
# Open frames
image1 = Image.open('image1.png')
image2 = Image.open('image2.png')
image3 = Image.open('image3.png')
# Paste frames
gif.paste(image1, (0, 0))
gif.paste(image2, (50, 50))
gif.paste(image3, (100, 100))
# Set frame delay (milliseconds)
gif.info['duration'] = 500
# Save GIF
gif.save('animation.gif', save_all=True, append_images=[image2, image3], loop=0)The script demonstrates how to control the delay between frames and generate a looping GIF file.
Additional examples illustrate common Pillow image‑processing operations:
Resize an image:
from PIL import Image
image = Image.open('input.jpg')
new_size = (800, 600)
resized_image = image.resize(new_size)
resized_image.save('output.jpg')Crop an image:
from PIL import Image
image = Image.open('input.jpg')
box = (100, 100, 400, 400) # (left, upper, right, lower)
cropped_image = image.crop(box)
cropped_image.save('output.jpg')Add a text watermark:
from PIL import Image, ImageDraw, ImageFont
image = Image.open('input.jpg')
draw = ImageDraw.Draw(image)
text = 'Watermark'
font = ImageFont.truetype('arial.ttf', size=50)
draw.text((10, 10), text, font=font)
image.save('output.jpg')Rotate an image:
from PIL import Image
image = Image.open('input.jpg')
angle = 45 # degrees counter‑clockwise
rotated_image = image.rotate(angle)
rotated_image.save('output.jpg')Apply a blur filter:
from PIL import Image, ImageFilter
image = Image.open('input.jpg')
filtered_image = image.filter(ImageFilter.BLUR)
filtered_image.save('output.jpg')These examples cover typical Pillow tasks; replace the placeholder file paths with your own images and ensure required fonts are installed for watermarking.
Test Development Learning Exchange
Test Development Learning Exchange
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.