DEV Community

Cover image for Resizing & cropping images using Python Pillow
Onelinerhub
Onelinerhub

Posted on

Resizing & cropping images using Python Pillow

We're going to use Image and ImageOps components of Pillow module to resize/crop image.

How to resize an image keeping aspect ratio

from PIL import Image, ImageOps

im = Image.open('/var/www/examples/heroine.png')
width = 100
height = width * im.size[1]/im.size[0]

im = im.resize((width, height))
Enter fullscreen mode Exit fullscreen mode
  • 100 - resized image width,
  • width * im.size[1]/im.size[0] - calculates height so that aspect ratio is maintained.

Open original or edit on Github.

How to crop an image from center

im = Image.open('/var/www/examples/heroine.png')
crop = (400, 400)
left = round((im.size[0] - crop[0])/2)
top = round((im.size[1] - crop[1])/2)
im = im.crop((left, top, crop[0]+left, crop[1] + top))
Enter fullscreen mode Exit fullscreen mode
  • (400, 400) - cropping area width and height,
  • (im.size[0] - crop[0])/2` - left coordinate of a crop area to position in the horizontal center,
  • (im.size[1] - crop[1])/2` - top coordinate of a crop area to position in the vertical center.

Open original or edit on Github.

How to resize/crop an image cropped to fit certain area (cover thumbnail)

im = Image.open('/var/www/examples/heroine.png')
im = ImageOps.fit(im, (100,100), Image.ANTIALIAS)
Enter fullscreen mode Exit fullscreen mode
  • 100,100 - thumbnail area width and height,
  • ImageOps.fit( - fits an image into given area.

Open original or edit on Github.

Top comments (0)