Image cropping is a basic feature for almost all apps that work with images. Since its setup is a bit more tricky than you might expect, we will skip the normal approach. We’ve got an API in mind that will take all the fight out of this one.
Let’s use pip install for our API client:
pip install cloudmersive-image-api-client
We next need to write out a function call for edit_crop_rectangle, which we can structure like this:
from __future__ import print_functionimport timeimport cloudmersive_image_api_clientfrom cloudmersive_image_api_client.rest import ApiExceptionfrom pprint import pprint# Configure API key authorization: Apikeyconfiguration = cloudmersive_image_api_client.Configuration()configuration.api_key['Apikey'] = 'YOUR_API_KEY'# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed# configuration.api_key_prefix['Apikey'] = 'Bearer'# create an instance of the API classapi_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/file' # file | Image file to perform the operation on. Common file formats such as PNG, JPEG are supported.try:# Crop an image to a rectangular areaapi_response = api_instance.edit_crop_rectangle(left, top, width, height, image_file)pprint(api_response)except ApiException as e:print("Exception when calling EditApi->edit_crop_rectangle: %s\n" % e)
Let’s specify our crop’s location and size, then input our image file. Just like that, we are done. We also have specialized cropping API functions that automatically find faces and crop the image to them in an either circular or rectangular shape. These are called face_crop_first_round and face_crop_first, respectively.