How to Draw Text onto Images in PHP
Overlaying text across an image is really useful, but it’s difficult to accomplish at scale. Thankfully, APIs make a big difference in situations like these — you can use the below API to programmatically draw text onto images at scale with customized visuals. You’ll just need to copy & paste from the PHP code examples provided below to structure your API call and authorize your requests with a free-tier API key (you can get one by registering a free account on our website).
To download the SDK, use the following command:
composer require cloudmersive/cloudmersive_imagerecognition_api_client
To structure your API call, use the examples below. In addition to your API key, your requests should include the image URL (or base image bytes), along with specifications for the text you want to overlay, including its font family, font size, color, location within the image (determined by X/Y pixel coordinates) and overall size (determined by width/height, expressed in terms of pixels):
<?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\EditApi(
new GuzzleHttp\Client(),
$config
);
$request = new \Swagger\Client\Model\DrawTextRequest(); // \Swagger\Client\Model\DrawTextRequest | Draw text parameters
try {
$result = $apiInstance->editDrawText($request);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling EditApi->editDrawText: ', $e->getMessage(), PHP_EOL;
}
?>
You can refer to the below example JSON to format your request:
{
"BaseImageBytes": "string",
"BaseImageUrl": "string",
"TextToDraw": [
{
"Text": "string",
"FontFamilyName": "string",
"FontSize": 0,
"Color": "string",
"X": 0,
"Y": 0,
"Width": 0,
"Height": 0
}
]
}