Resize an Image while Preserving Aspect Ratio in Python
When we change the width & height of a photo during the editing process, it’s important to know ahead of time if we want to preserve the photo’s original aspect ratio in the new version. This ratio influences the look & feel of an image, regardless of its actual size. Using the Cloudmersive Image API, you can automatically scale a photo to a specified maximum width & height, preserving aspect ratio. Connecting to this API is made easy with ready-to-run code available on the Cloudmersive API console page. Below, I’ll walk you through connecting in Python.
You can kick things off by running the below command, which will install the Python SDK:
pip install cloudmersive-image-api-client
After that, use the below code to call the API, and you’re all set to go. Make sure to authenticate your API key and specify the maximum width & height of the new photo where indicated, respectively:
from __future__ import print_function
import time
import cloudmersive_image_api_client
from cloudmersive_image_api_client.rest import ApiException
from pprint import pprint# Configure API key authorization: Apikey
configuration = cloudmersive_image_api_client.Configuration()
configuration.api_key['Apikey'] = 'YOUR_API_KEY'# create an instance of the API class
api_instance = cloudmersive_image_api_client.ResizeApi(cloudmersive_image_api_client.ApiClient(configuration))
max_width = 56 # int | Maximum width of the output image - final image will be as large as possible while less than or equial to this width
max_height = 56 # int | Maximum height of the output image - final image will be as large as possible while less than or equial to this height
image_file = '/path/to/inputfile' # file | Image file to perform the operation on. Common file formats such as PNG, JPEG are supported.try:
# Resize an image while preserving aspect ratio
api_response = api_instance.resize_post(max_width, max_height, image_file)
pprint(api_response)
except ApiException as e:
print("Exception when calling ResizeApi->resize_post: %s\n" % e)