Create images with PIL and abstract the code

PIL, images and functions

Let’s see how to create images with color with PIL (pip install pillow), a module made to manipulate images in Python. We will create a simple image, pasting three different images with three different colors to make a flag, the italian one. Then we will abstract the code so that we can make all the three color flag we want of every size. We will see how useful is to put our code in functions, so that we can use the code more times without having to write lots of lines. This makes the code much more readeable and easy to manage.

from PIL import Image

def flag(c,w=100,h=100):
	c1,c2,c3 = c.split()
	img = Image.new("RGB", (w*3,h), c1)
	lay1 = Image.new("RGB", (w,h), c2)
	lay2 = Image.new("RGB", (w,h), c3)
	img.paste(lay1,(w,0))
	img.paste(lay2,(w*2,0))
	img.show()

flag("gold blue pink",200,350)

Here is the live coding video of the code above.


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.