Python PIL – Crop an image

In this post we will be creating a Python script that will crop an existing image, to do this we will be using the Python Imaging Library also known as PIL enabling us to image processing capabilities.

See the sample of Python code where we utilise the PIL library to crop an image to a predefined size and save it as a new file. To help us achieve this we utilize the ‘img.crop()’ method which crops the input image with the provided coordinates.

Here the X,Y coordinates are set to 0,0 meaning we’ll be cropping towards the very top left of the image. Our width and height of the crop are set to 150, 125 pixels.

from PIL import Image'image.png')

img=img.crop((0, 0, 150, 125))'cropped_image.png')

See below our image before cropping.

Python PIL Crop an image before

See below our cropped image.

Python PIL Crop an image after

Take a look at some of our other content around the Python programming language by clicking here.

Leave a Reply