How to Resize an Image Maintaining Aspect Ratio in PHP

Cloudmersive
2 min readMay 1, 2024

We can easily resize image uploads without impacting the original aspect ratio by calling a free image resizing API in PHP.

All we need to do is set maximum height ($max_height) and maximum width ($max_width) values in our API request, and all the images we process will scale as much as possible to those values without breaking the original aspect ratio.

The simplicity of this solution beats writing a ton of new code, especially if we’re just trying to fit a simple, reliable, and low-code solution into our image upload process.

We can structure our API call in two quick steps. First, let’s install the PHP client via Composer by executing the below command from the command line:

composer require cloudmersive/cloudmersive_imagerecognition_api_client

Next, let’s turn our attention to API call authorization. We’ll need a free Cloudmersive API key to authorize our requests (these allow a limit of 800 API calls per month with zero commitments).

Let’s now copy the below code to call the function, and let’s customize our $max_height and $max_width parameters:

<?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;
}
?>

That’s all the code we’ll need! Now we can easily resize our images without worrying about breaking the original aspect ratio.

--

--

Cloudmersive

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