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 img=Image.open('image.png') img=img.crop((0, 0, 150, 125)) img.save('cropped_image.png')
See below our image before cropping.
See below our cropped image.
Take a look at some of our other content around the Python programming language by clicking here.