Sling Academy
Home/Python/Python – Using Pillow to generate images programmatically

Python – Using Pillow to generate images programmatically

Last updated: January 07, 2024

Overview

Creating images programmatically is a critical skill for many developers, designers, and content creators. Pillow, an offshoot of the Python Imaging Library (PIL), simplifies image processing tasks in Python. In this tutorial, we’ll explore how to use Pillow to generate images, manipulate them, apply filters, and save the results.

Getting Started with Pillow

Before we jump into generating images, you need to have Python installed on your machine and Pillow added to your Python environment:

pip install Pillow

With Pillow installed, let’s create a basic image:

from PIL import Image

# Setting the size of the image
size = (400, 300)

# Creating a new image with RGB mode
new_image = Image.new('RGB', size, color='white')

# Save the image
new_image.save('new_image.png')

We’ve created a simple white image. But that’s just the beginning. Let’s add some customization.

Customizing Images

We can start by drawing shapes or writing text onto our image:

from PIL import Image, ImageDraw, ImageFont

# Create an image with a blue background
image_with_background = Image.new('RGB', size, 'blue')

draw = ImageDraw.Draw(image_with_background)

draw.rectangle(
    [(50, 50), (100, 100)], 
    fill='yellow', 
    outline='black'
)

draw.text(
    (150, 75), 
    'Hello World!', 
    fill='white', 
    font=ImageFont.truetype('arial.ttf', size=20)
)

# Save the customized image
image_with_background.save('custom_image.png')

Now we’ve added a rectangle and text to our image. See the sky as the limit; you can draw anything from lines to complex shapes.

Working with Existing Images

Pillow isn’t just for creating new images; it’s incredibly powerful when used to manipulate existing ones:

# Open an existing image
original_image = Image.open('existing_image.png')

# Apply a blur filter
blurred_image = original_image.filter(ImageFilter.BLUR)

# Save the blurred image
blurred_image.save('blurred_image.png')

You can crop, rotate, resize, and apply a variety of filters to achieve your desired outcome.

More Complex Manipulations

Pillow also allows for more complex image operations such as merging images or generating thumbnails:

# Generating a thumbnail
thumbnail_size = (100, 100)
original_image.thumbnail(thumbnail_size)
original_image.save('thumbnail.png')

# Merging two images
other_image = Image.open('other_image.png')
merged_image = Image.blend(original_image, other_image, alpha=0.5)
merged_image.save('merged_image.png')

Here we used Pillow’s thumbnail and blend functions to modify the image size and to merge two images, respectively.

Creating Image Sequences

With Pillow, you can also create sequences of images for animations and gifs:

from PIL import ImageSequence

# Create an animation sequence
frames = [new_image, image_with_background, merged_image]
frames[0].save('animation.gif', save_all=True, append_images=frames[1:], duration=100, loop=0)

This creates a simple GIF by cycling through our image frames.

Advanced Features

Pillow’s reach goes beyond simple image manipulation. For instance, let’s explore color channels and histograms:

# Splitting into color channels
r, g, b = original_image.split()

# Generating a histogram
histogram = original_image.histogram()
print(histogram)

This code separates the different color channels and produces a histogram representing the distribution of colors in an image.

Conclusion

We’ve only scratched the surface of what Pillow can do in terms of generating and manipulating images in Python. With its vast array of functionality, Pillow proves to be a powerful tool in a programmer’s toolbox for any image processing or generation task. As you advance, you’ll discover even more complex and nuanced ways to create visually compelling content.

Next Article: Python: Adding watermark to images using Pillow

Previous Article: Python: Crawling HTML tables and save to CSV files

Series: Python – Fun Examples

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types