How can the PHP code be optimized to ensure proper image generation with different fonts and text alignment using the GD library?
To optimize PHP code for proper image generation with different fonts and text alignment using the GD library, you can create a function that takes parameters for text, font file, font size, text color, background color, and text alignment. Inside the function, you can set the font, allocate colors, calculate text positioning based on alignment, and finally, write the text onto the image.
function generateImageWithText($text, $fontFile, $fontSize, $textColor, $bgColor, $alignment) {
$image = imagecreate(400, 200);
$bgColor = imagecolorallocate($image, $bgColor[0], $bgColor[1], $bgColor[2]);
$textColor = imagecolorallocate($image, $textColor[0], $textColor[1], $textColor[2]);
$fontPath = 'path/to/fonts/' . $fontFile;
$textWidth = imagettfbbox($fontSize, 0, $fontPath, $text);
$textHeight = $textWidth[1] - $textWidth[7];
switch ($alignment) {
case 'left':
$x = 10;
break;
case 'center':
$x = (400 - $textWidth[2]) / 2;
break;
case 'right':
$x = 400 - $textWidth[2] - 10;
break;
}
$y = (200 - $textHeight) / 2 + $textHeight;
imagettftext($image, $fontSize, 0, $x, $y, $textColor, $fontPath, $text);
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
}
generateImageWithText('Hello World!', 'arial.ttf', 20, [255, 255, 255], [0, 0, 0], 'center');