How to Convert Images to JPG Format in PHP
Online image files are generally stored in one of several common formats (including JPG, PNG, WEBP, etc.), and JPG is the most universally compatible among those. Thankfully, using the ready-to-run PHP code below, you can quickly and easily take advantage of a free API which automatically converts dozens of common image formats (see a complete list here) to JPG.
First, run this command to install the SDK:
composer require cloudmersive/cloudmersive_imagerecognition_api_client
Then use the remaining code examples to structure your API call, with file path included in the $image_file line:
<?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\ConvertApi(
new GuzzleHttp\Client(),
$config
);
$quality = 56; // int | Set the JPEG quality level; lowest quality is 1 (highest compression), highest quality (lowest compression) is 100; recommended value is 75
$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->convertToJpg($quality, $image_file);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling ConvertApi->convertToJpg: ', $e->getMessage(), PHP_EOL;
}
?>
Lastly, to authenticate your request, include a free-tier API key where indicated in the $config line (you can get one by registering a free account on our website).
After that, you’re all done — no more code required!