How to Resize an Image in PHP
To resize image uploads without writing a ton of complex code, we can simply call a free image resizing API with complementary PHP examples.
Structuring our API call is extremely easy. We can install the PHP client via composer by executing the below command from our command line:
composer require cloudmersive/cloudmersive_imagerecognition_api_client
And we can call the function using the ready-to-run PHP code examples below:
<?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
);
$width = 56; // int | Width of the output image - final image will be exactly this width
$height = 56; // int | Height of the output image - final image will be exactly 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->resizeResizeSimple($width, $height, $image_file);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling ResizeApi->resizeResizeSimple: ', $e->getMessage(), PHP_EOL;
}
?>
To authorize our requests for free, we’ll just need a free Cloudmersive API key, which will give us a limit of 800 API calls per month with no additional commitments.
We can now easily set $height
and $width
parameters for our image resizing request and standardize image size for any image upload process.