DEV Community

loading...
Cover image for Image effects with python

Image effects with python

petercour
・1 min read

The module PIL can be used to change images. You can load an image, resize it to any size. You can apply effects (like image blur) and more.

So how does that work?

First you need an image to change. Lets say this image

Save it as image.png

Resize image

Resize an image is very easy. Load the image, get the width and height. Then apply the thumbnail method. Finally you can change the image format (jpg)

#!/usr/bin/python3
import PIL.Image
im = PIL.Image.open('image.png')
w, h = im.size
im.thumbnail((w//2, h//2))
im.save('image_resize.png', 'jpeg')

Run it, you'll see the image changed

Blur image

To blur an image use the code below. This type of effect works by applying a filter (matrix) to the image. In the case it's applied using the method im.filter():

#!/usr/bin/python3
import PIL.Image, PIL.ImageFilter
im = PIL.Image.open('image.png')
im2 = im.filter(PIL.ImageFilter.BLUR)
im2.save('image-blur.png', 'jpeg')

Run to see blur effect applied

Resources:

Discussion (0)