Crop an image in Python

Get the four numbers in the box right, then crop to the centre, a square or any ratio.

To crop an image in Python, call crop on a Pillow image with a box of four numbers. The method is simple. The box is where almost everyone goes wrong the first time.

The short answer

from PIL import Image

img = Image.open("photo.jpg")
print(img.size)  # (1200, 800)

cropped = img.crop((200, 150, 1000, 650))
cropped.save("cropped.jpg")

print(cropped.size)  # (800, 500)

crop returns a new image and leaves the original alone. If you have not installed Pillow yet, Pillow in Python covers that.

The box tuple: left, upper, right, lower

The box is (left, upper, right, lower), measured in pixels from the top-left corner of the image. left and upper are the coordinates of the top-left corner of the area you want. right and lower are the coordinates of its bottom-right corner. They are not a width and a height.

So the size of the result is right - left by lower - upper. In the example above that is 1000 - 200 = 800 wide and 650 - 150 = 500 tall.

Most other tools, CSS and image editors included, describe a rectangle as x, y, width, height, and people carry that habit over. Pillow does not complain. It just gives you a different rectangle:

wrong = img.crop((200, 150, 800, 500))
print(wrong.size)  # (600, 350)

If you think in x, y, width, height, convert on the way in:

x, y, width, height = 200, 150, 800, 500

right_size = img.crop((x, y, x + width, y + height))
print(right_size.size)  # (800, 500)

Three more things about the box are worth knowing:

  • The y axis runs downwards, so upper is the smaller number and lower the larger.
  • If right is less than left, Pillow raises ValueError: Coordinate 'right' is less than 'left'.
  • A box that runs past the edge of the image is not an error. You get the size you asked for, with the overflow filled in black. If a crop has a black strip down one side, this is why.

Centre crop

Work out how much to trim, split it evenly, and build the box from there:

def center_crop(img, width, height):
    left = (img.width - width) // 2
    upper = (img.height - height) // 2
    return img.crop((left, upper, left + width, upper + height))


print(center_crop(img, 600, 600).size)  # (600, 600)

Crop to a square or an aspect ratio

To crop to a shape, keep as much of the image as possible and trim only the side that is too long. A ratio is width divided by height, so a square is 1 and widescreen is 16 / 9:

def crop_to_ratio(img, ratio):
    width, height = img.size
    if width / height > ratio:
        width = round(height * ratio)
    else:
        height = round(width / ratio)
    return center_crop(img, width, height)


print(crop_to_ratio(img, 1).size)       # (800, 800)
print(crop_to_ratio(img, 16 / 9).size)  # (1200, 675)
print(crop_to_ratio(img, 4 / 5).size)   # (640, 800)

Crop and resize in one step with ImageOps.fit

Most of the time a crop is followed by a resize, because what you really want is "a 400 pixel square avatar". ImageOps.fit does both. It scales the image until it covers the target size, then trims the overflow:

from PIL import ImageOps

avatar = ImageOps.fit(img, (400, 400))
print(avatar.size)  # (400, 400)

By default it keeps the centre. The centering argument moves the kept area: (0.5, 0.5) is the middle, (0.5, 0.0) keeps the top edge, which suits portraits where the face sits near the top.

top = ImageOps.fit(img, (400, 400), centering=(0.5, 0.0))

One thing to watch: fit will enlarge an image that is smaller than the target, and enlarged images look soft. Check img.size first if your sources vary.

The shorter way with Nitro Image

Nitro Image wraps Pillow and replaces the box with a size and an anchor. Its class is called Image too, so import it under a different name when Pillow is in the same file:

from nitro_img import Image as NitroImage

NitroImage("photo.jpg").crop(500, 400, anchor="center").save("crop.jpg")
NitroImage("photo.jpg").crop(500, 400, anchor="top-left").save("corner.jpg")
NitroImage("photo.jpg").cover(400, 400).save("square.jpg")

crop takes the width and height you want and an anchor such as "center", "top" or "bottom-right". cover is the scale-then-trim behaviour of ImageOps.fit. Because the calls chain, you can add .webp() before .save() and convert in the same line.

It does not replace the box, though. When you need an exact region, such as a face a detector found or a tile cut from a sprite sheet, you need coordinates, and Pillow's crop is the right tool. For a single centre crop in a script, ImageOps.fit is already one line.

Common questions

Does crop change the original image? No. It returns a new image. The file on disk only changes if you save over it.

How do I crop without losing JPEG quality? Every JPEG save recompresses the picture. Save with a high quality, such as 90 or more, or save the crop as PNG if it must be exact.

How do I cut an image in half? Use the image's own size in the box: img.crop((0, 0, img.width // 2, img.height)) is the left half.

Is the crop lazy? Yes. Pillow does not copy the pixels until you use the result. If you plan to close or change the source image afterwards, call .load() on the crop first.

This page uses Nitro Image.

Resize, convert, and optimise images with a chainable API. Generate responsive sizes in one call.

$ pip install nitro-image