How to Scale, Resize Images While Maintaining Aspect Ratio in PHP

Cloudmersive
2 min readMar 10, 2023

--

When resizing images, we can either specify custom dimensions or preserve the original aspect ratio (height to width ratio). While customizing dimensions helps fit platform-specific recommendations, preserving aspect ratio ensures we only impact the scale of an image and not the overall aesthetic.

To easily this workflow in your applications, you can call our Resize Image, Preserve Aspect Ratio API for free using the PHP code examples provided below in this article. You’ll just need to register a free account on our website first, and use your free-tier API key to authenticate each request (free accounts provide a limit of 800 API calls per month).

To install the SDK, use the following command:

composer require cloudmersive/cloudmersive_imagerecognition_api_client

After that, use the remaining code to structure your API call:

<?php
require_once(__DIR__ . '/vendor/autoload.php');

// Configure API key authorization: Apikey
$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('Apikey', 'YOUR_API_KEY');



$apiInstance = new Swagger\Client\Api\ResizeApi(


new GuzzleHttp\Client(),
$config
);
$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"; // \SplFileObject | Image file to perform the operation on. Common file formats such as PNG, JPEG are supported.

try {
$result = $apiInstance->resizePost($max_width, $max_height, $image_file);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling ResizeApi->resizePost: ', $e->getMessage(), PHP_EOL;
}
?>

Just like that, you’re all done — no more code required!

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

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

No responses yet