DEV Community

Cover image for 5 examples of using Pillow to manipulate images in Python
Onelinerhub
Onelinerhub

Posted on

5 examples of using Pillow to manipulate images in Python

1. How to automatically tune image contrast

from PIL import Image, ImageOps

im = Image.open('/var/www/examples/heroine.png')

im = ImageOps.autocontrast(im, cutoff = 5)
im.show()
Enter fullscreen mode Exit fullscreen mode
  • ImageOps.autocontrast - set contrast automatically based on given cutoff,
  • cutoff = 5 - defines part of histogram (in percents) that should be removed,

Open original or edit on Github.

2. How to convert an image to a black-and-white color scheme

from PIL import Image, ImageFilter

im = Image.open('/var/www/examples/heroine.png')
im = im.convert('1')

im.show()
Enter fullscreen mode Exit fullscreen mode
  • .convert('1') - convert image to black and white colors,

Open original or edit on Github.

3. How to load an image over internet

from PIL import Image
import requests
from io import BytesIO

url = 'https://examples.onelinerhub.com/heroine.png'

response = requests.get(url)
img = Image.open(BytesIO(response.content))

im.show()
Enter fullscreen mode Exit fullscreen mode
  • requests.get - loads data from given url,
  • response.content - get content previously loaded from url,

Open original or edit on Github.

4. How to rotate an image without cropping it

from PIL import Image, ImageEnhance

im = Image.open('/var/www/examples/heroine.png')
im = im.rotate(90, expand=True)

im.show()
Enter fullscreen mode Exit fullscreen mode
  • expand=True - increase image size instead of cropping while rotating,

Open original or edit on Github.

5. How to add rotated text to an image

The idea here is to create 2 images - one to add text to and another with the text itself. This way we can rotate second image and merge them to get desired effect.

from PIL import Image, ImageDraw, ImageFont

im = Image.open('/var/www/examples/heroine.png')
text = "I am hero"

tim = Image.new('RGBA', (500,200), (0,0,0,0))
dr = ImageDraw.Draw(tim)
ft = ImageFont.truetype('/var/www/examples/roboto.ttf', 100)
dr.text((0, 0), text, font=ft, fill=(200, 200, 0))

tim = tim.rotate(30,  expand=1)

im.paste(tim, (0,0), tim)
im.show()
Enter fullscreen mode Exit fullscreen mode
  • .text( - draws text with given params,
  • .rotate( - rotate given image,
  • .paste( - paste image with text on top of loaded image,

Open original or edit on Github.

Top comments (0)