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

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots