Crop Images in Python

Image cropping is an essential feature in image editing and graphics designing applications. It lets you resize the images and trim off their edges. While processing images or dealing with image editing in Python applications, developers often require an effortless image cropping mechanism. So in this blog post, we will learn how to crop images seamlessly in a Python application.

Python Library to Crop Images

For image cropping, we will use Aspose.Imaging for Python. It is a versatile library that provides a range of features for working with images. Particularly, it lets you perform basic as well as advanced image editing tasks with ease.

You can either download the library or install it into your Python applications from PyPI.

> pip install aspose-imaging-python-net 

Cropping an Image in Python

There are two ways to crop an image using Aspose.Imaging for Python: using shift values and using a rectangle. In the shift values method, we specify left, right, top, and bottom values for image shift. On the other hand, we use a rectangle to define the cropping area in the second method.

So let’s go through each of the above-stated image cropping methods with the help of Python code snippets.

Crop an Image with Shift Values in Python

The steps below demonstrate how to crop an image using shift values in Python.

  • First, use Image.load() method to load the image as a RasterImage.
  • Then, cache the image for better performance.
  • Specify the left, right, top, and bottom shift values.
  • Pass the shift values to RasterImage.crop() method and crop the image.
  • Finally, save the cropped image using RasterImage.save() method.

The following code snippet shows how to crop an image in Python.

Below are the screenshots of the input image (first) and its cropped version (second).

crop image in Python
image cropping in Python

Image Cropping with a Rectangle

In this method, we define a rectangle to crop a particular area in the loaded image. The resultant image contains the portion of the image that comes inside that rectangle. The following are the steps to crop an image using a rectangle.

The following code snippet shows image cropping with a rectangle in Python.

Get Free Python Image Cropping Library

You can get a free temporary license and crop images without evaluation limitations.

Conclusion

Aspose.Imaging for Python provides a robust solution for image cropping and manipulation. This blog post provided you with a couple of image cropping methods that you can easily integrate into your Python applications. Enhance your image processing capabilities with this powerful Python image editing API. Explore its amazing features by visiting the documentation and share your queries with us via our forum.

See Also