Resize a Video & Preserve Aspect Ratio in PHP
Resizing videos benefits our website’s loading speeds & aesthetic uniformity in much the same way resizing images does. Thankfully, you can quickly & easily implement your own custom video-resizing process using the free code examples provided below in this article.
Our Video Aspect Ratio resizing API allows you to customize maximum height or width values to control the scale of your video uploads, and it additionally allows you to specify your output videos’ new frame rate and quality.
Before we structure our API call, let’s first install the client SDK by running the below command:
composer require cloudmersive/cloudmersive_video_api_client
Now let’s copy & paste from the following code (provided here in PHP; alternative code examples available on our swagger documentation page) to structure our request, and let’s authenticate access by grabbing a free-tier API key from the Cloudmersive website (register a free account to get one; this comes wtih a limit of 800 API calls per month & no additional commitments).
<?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\VideoApi(
new GuzzleHttp\Client(),
$config
);
$input_file = "/path/to/inputfile"; // \SplFileObject | Input file to perform the operation on.
$file_url = "file_url_example"; // string | Optional; URL of a video file being used for conversion. Use this option for files larger than 2GB.
$max_width = 56; // int | Optional; Maximum width of the output video, up to the original video width. Defaults to original video width.
$max_height = 56; // int | Optional; Maximum height of the output video, up to the original video width. Defaults to original video height.
$frame_rate = 56; // int | Optional; Specify the frame rate of the output video. Defaults to original video frame rate.
$quality = 56; // int | Optional; Specify the quality of the output video, where 100 is lossless and 1 is the lowest possible quality with highest compression. Default is 50.
$extension = "extension_example"; // string | Optional; Specify the file extension of the input video. This is recommended when inputting a file directly, without a file name. If no file name is available and no extension is provided, the extension will be inferred from the file data, which may cause a different extension to be used in the output.
try {
$result = $apiInstance->videoResizeVideo($input_file, $file_url, $max_width, $max_height, $frame_rate, $quality, $extension);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling VideoApi->videoResizeVideo: ', $e->getMessage(), PHP_EOL;
}
?>
That’s all there is to it! Please note it’s recommended to configure the $extension field when inputting a file directly without a file name.