Crop an Image to a Rectangular Area in Python

2 min readFeb 7, 2022


With the ‘Edit’ iteration of the Cloudmersive Image API, you can slice & dice target rectangular areas of an input image with specified pixel amounts. Cropping an image in this way requires a few specific parameters to accomplish, but the rest is made easy with copy & paste code available on the Cloudmersive API console. Let’s walk through the steps to connect to this API iteration in a Python environment.

For starters, run this command to install the Python SDK:

pip install cloudmersive-image-api-client

Next, you can begin the callback function with the below snippet:

from __future__ import print_function
import time
import cloudmersive_image_api_client
from import ApiException
from pprint import pprint

For the following step, you’ll need to have your Cloudmersive API key handy & copy that into the snippet below. If you don’t already have a key, visit the Cloudmersive website & make a free account to receive one (this account will enable 800 free monthly API calls).

# Configure API key authorization: Apikey
configuration = cloudmersive_image_api_client.Configuration()
configuration.api_key['Apikey'] = 'YOUR_API_KEY'

Finally, you can finish up with the final snippet here. Note that you’ll need to specify the size of the cropped area of the image along with inputting the input image file.

# create an instance of the API class
api_instance = cloudmersive_image_api_client.EditApi(cloudmersive_image_api_client.ApiClient(configuration))
left = 56 # int | The left edge of the rectangular crop area in pixels (X).
top = 56 # int | The top edge of the rectangular crop area in pixels (Y).
width = 56 # int | The width of the rectangular crop area in pixels.
height = 56 # int | The height of the rectangular crop area in pixels.
image_file = '/path/to/inputfile' # file | Image file to perform the operation on. Common file formats such as PNG, JPEG are supported.
# Crop an image to a rectangular area
api_response = api_instance.edit_crop_rectangle(left, top, width, height, image_file)
except ApiException as e:
print("Exception when calling EditApi->edit_crop_rectangle: %s\n" % e)




There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.