Resizing & cropping images using Python Pillow
Onelinerhub
Posted on October 27, 2022
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))
-
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))
-
(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)
-
100,100
- thumbnail area width and height, -
ImageOps.fit(
- fits an image into given area.
💖 💪 🙅 🚩
Onelinerhub
Posted on October 27, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.