A brief guide to PIL, python image library

What is PIL

PIL is a powerful module for Python that allows you to create and elaborate images by conding in Python. You can do almost anything, building the perfect image tools for your needs.We will take a fast look at the main functions of this very useful module.

Install

First you need to install pil’s fork pillow:pip install pillow

Import

The first thing you need to import is the Class Image
>>> from PIL import Image

Create

>>> img = Image.new(‘RBG’, (200,200), ‘yellow’)

This will create a yellow square image of 200 px of width and 200 px of height. RGB is for Red, Green and Blue, aka the image is in color. If you want to use transparency you have to use RGBA instead of RGB.

Open

>>> img = Image.open(‘existing.png’)

Save

>>> img.save(‘myimage.png’)

Show

>>> img.show()

Resize

>>> img.resize((100,100), Image.ANTIALIAS)

Filters for the images

>>> img.filter(ImageFilter.BLUR)

There’s a much smoother blur called SMOOTH
>>> i = i.filter(ImageFilter.SMOOTH )

You can then create a ‘contour’ effect
>>> i = i.filter( ImageFilter.CONTOUR )

Blend 2 images together

>>> img = Image.blend(Image.open(‘image1.png’,’image2.png’, 0.5) )

Pasting an image on another

>>> img.paste((0,0),’image2.png’)

Write text on an image (ImageDraw)

>>> draw = ImageDraw.Draw(img)
>>> draw.text(0,0,’This text goes on top of the image’)

Thumbnail

>>> im.thumbnail((128, 128), Image.ANTIALIAS)

text and font

To add a text to an image after you created an image:
>>> im = img.new(“RGBA”, (600,400), “yellow”)

You create a ImageDraw.Draw object to wich you pass the im object you created and on wich you draw:
>>> d = ImageDraw.Draw(im)

Now you are ready to add a text to the d object, but you can define the size and family of the text, using the ImageFont class (that you need to import from PIL) together with the method truetype:


>>>
font = ImageFont.truetype(“Arial 20”)

Now, you can finally add this font to the font argument when you add the text like this:

>>> d.text((10,10), “text to show”, (255,255,255), font=font)

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.