DEV Community

Cover image for Generate images with Python PIL
petercour
petercour

Posted on

Generate images with Python PIL

You can create your own images with Python code. So how do you start?
First use the PIL module.

The Python Image Library (PIL) lets you work with images in Python.

To create an image of 128x128 pixels with the color red (#FF0000) use:

#!/usr/bin/python3
from PIL import Image

im= Image.new("RGB", (128, 128), "#FF0000")
im.show()
im.show()
Enter fullscreen mode Exit fullscreen mode

Creates the image:

For green and blue you can use "#0000FF" or "#00FF00". It also accepts keywords like "green".

im= Image.new("RGB", (128, 128),"green")
Enter fullscreen mode Exit fullscreen mode

To change a single pixel:

#!/usr/bin/python3
# change pixel                                                                             
pixels = im.load()
pixels[10,10] = (0,0,0)
Enter fullscreen mode Exit fullscreen mode

You can add rectangles to the image:

#!/usr/bin/python3
from PIL import Image

im= Image.new("RGB", (128, 128), "#FF0000")
im.paste((256,256,0),(0,0,100,100))
im.show()
Enter fullscreen mode Exit fullscreen mode

Then

You can do effects like

#!/usr/bin/python3
from PIL import Image

im= Image.new("RGB", (128, 128), "#FF0000")
for i in range(0,256):
    im.paste((256-i,256-i,256-i),(i,i,128,128))
im.show()
Enter fullscreen mode Exit fullscreen mode

Then

Related links:

Top comments (1)

Collapse
 
autoferrit profile image
Shawn McElroy • Edited

PIL has been maintained for some time. You should be using pillow.

However I think there should be API partity but I'm not sure if it's in a drop in replacement or not.

But it's always good to k ow how to use this stuff.