DEV Community

Cover image for Generate images with Python PIL
petercour
petercour

Posted on

8 2

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:

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

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.

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay