I am a DIY blogger, and the most tedious part of the job is editing the images. I am constantly repeating the following steps:
- Resize the image
- Add a text watermark
- Compress the image
I wanted to automate the process. There are good solutions out there for automating image manipulation, but it has been a few years since I last wrote a meaningful piece of Python code. I saw this as an excellent way to dust off my Python skill and learn a bit about programmatic image manipulation.
Related:
Pillow, the friendly PIL fork
Pillow is an active fork of PIL, the Python Imaging Library. With Pillow, you can programmatically edit image files in Python. To get started with Pillow, install the binary with pip:
pip install Pillow
The core component of the Python Imaging Library is the Image
module. With Image
, you can open and save images, create new images, resize images and read the image metadata.
from PIL import Image
image = Image.open('cats.png')
print(image.size, image.format)
# (350, 250) PNG
ImageDraw and ImageFont
In addition to Image, the ImageDraw and ImageFont modules are necessary to watermark an image. The ImageDraw module adds functionality for drawing 2D graphics onto new or existing images. The ImageFont module is used for loading bitmap, TrueType and OpenType font files.
To draw text onto an image, get a drawing context from ImageDraw.Draw. The drawing context has a text method that will draw a string at the given position. To determine the size of the text, call the textsize method and it will return a tuple containing the text’s width and height.
from PIL import Image, ImageDraw, ImageFont
image = Image.open('cats.png')
width, height = image.size
draw = ImageDraw.Draw(image)
text = "A watermark"
font = ImageFont.truetype('arial.ttf', 12)
textwidth, textheight = draw.textsize(text, font)
# calculate the x,y coordinates of the text
margin = 5
x = width - textwidth - margin
y = height - textheight - margin
# draw watermark in the bottom right corner
draw.text((x, y), text, font=font)
image.save('cats.png')
In addition to watermarking the images, my script had the requirement of resizing and compressing the images. The Image class has a resize method that takes a tuple containing values for width and height. To compress the images, I used the Tinify API.
marker.py
The first version my Python image manipulation script is complete. There are a couple things that I would like to tweak, but in it’s current form the script already saves me a lot of time and effort!
CLICK HERE to check out some of our other posts!
Dave Beck says
This is very cool and could save me a lot of time. I’m heading over to github to check it out. Thanks Ashley!