Crop Images with PIL/Pillow

# Import Pillow:
from PIL import Image

# Load the original image:
img = Image.open("flowers.jpg")

original image

100px * 100px, starting at the top-left corner

img2 = img.crop((0, 0, 100, 100))
img2.save("img2.jpg")

100x100 from top-left

100px * 100px, starting at the bottom-right corner

width = img.size[0]
height = img.size[1]
img3 = img.crop(
    (
        width - 100,
        height - 100,
        width,
        height
    )
)
img3.save("img3.jpg")

100x100 from bottom-right

100px * 150px, starting in the center

half_the_width = img.size[0] / 2
half_the_height = img.size[1] / 2
img4 = img.crop(
    (
        half_the_width - 50,
        half_the_height - 75,
        half_the_width + 50,
        half_the_height + 75
    )
)
img4.save("img4.jpg")

100x150 from center

Pad the image to a square

longer_side = max(img.size)
horizontal_padding = (longer_side - img.size[0]) / 2
vertical_padding = (longer_side - img.size[1]) / 2
img5 = img.crop(
    (
        -horizontal_padding,
        -vertical_padding,
        img.size[0] + horizontal_padding,
        img.size[1] + vertical_padding
    )
)
img5.save("img5.jpg")

pad image

About this Entry

Related Content


Comments