<?php
declare(strict_types=1);
// Error reporting
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
/**
* Check if GD and FreeType are available
*
* @return void
* @throws RuntimeException if GD or FreeType are not available
*/
function checkRequirements(): void
{
if (!extension_loaded('gd') || !function_exists('gd_info')) {
throw new RuntimeException("GD library is not enabled.");
}
$gdInfo = gd_info();
if (!isset($gdInfo['FreeType Support']) || !$gdInfo['FreeType Support']) {
throw new RuntimeException("FreeType support is not enabled.");
}
}
/**
* Generate an image with text
*
* @param string $text
* @param string $fontPath
* @return GdImage
* @throws RuntimeException if image creation fails
*/
function generateImage(string $text, string $fontPath): GdImage
{
if (!file_exists($fontPath) || !is_readable($fontPath)) {
throw new RuntimeException("Font file not found or not readable: $fontPath");
}
$width = 400;
$height = 200;
$im = imagecreatetruecolor($width, $height);
if ($im === false) {
throw new RuntimeException("Failed to create image");
}
$white = imagecolorallocate($im, 255, 255, 255);
$red = imagecolorallocate($im, 255, 0, 0);
imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $white);
// Calculate text position to center it
$fontSize = 20;
$bbox = imagettfbbox($fontSize, 0, $fontPath, $text);
$x = ceil(($width - $bbox[2]) / 2);
$y = ceil(($height - $bbox[5]) / 2);
imagettftext($im, $fontSize, 0, $x, $y, $red, $fontPath, $text);
return $im;
}
try {
checkRequirements();
$fontPath = __DIR__ . '/calibrib.ttf';
$text = 'Testing...';
$image = generateImage($text, $fontPath);
header('Content-Type: image/jpeg');
imagejpeg($image);
} catch (Exception $e) {
header("HTTP/1.1 500 Internal Server Error");
echo "An error occurred: " . $e->getMessage();
} finally {
if (isset($image) && $image instanceof GdImage) {
imagedestroy($image);
}
}