PCHomepage
Programmer
Some time ago I created a function for building font-based images on one of my sites and it is working fine but now I need to repurpose it for another site that sometimes needs to use two different fonts to create the image.
Using the GD library (Imagick is not available), can someone help me to add a second Truetype font to it so that a single image is created using both? Here is the existing single-font function which also calls other custom functions to provide drop-shadows etc.
I am calling the function with the code below and note that the "/" is part of the text string but it is also the separation between the fonts and will probably be presenting using the second font:
Using the GD library (Imagick is not available), can someone help me to add a second Truetype font to it so that a single image is created using both? Here is the existing single-font function which also calls other custom functions to provide drop-shadows etc.
PHP:
function textimage($String,$FontName1,$FontName2,$FontSize,$Angle,$EnableShadow,$CenterAlign) {
global $Height;
$FontPath = $_SERVER['DOCUMENT_ROOT'] . "/functions/truetype/";
$Font1 = $FontPath . $FontName1;
$Font2 = $FontPath . $FontName2;
$String = html_entity_decode($String);
$TextDimensions = imagettfbbox($FontSize,$Angle,$Font1,$String);
$Width = abs($TextDimensions[4] - $TextDimensions[0] + 5);
$Height = abs($TextDimensions[5] - $TextDimensions[1]) + 10;
$y_offset = abs($TextDimensions[5]);
$Image = imageCreateTransparent($Width,$Height);
imagesavealpha($Image, TRUE);
$TextColor = imagecolorallocate($Image,255,204,153);
$ShadowColor = imagecolorallocate($Image,119,119,119);
if ($EnableShadow === TRUE):
if ($CenterAlign === TRUE):
$x_offset = CenterText($FontSize,$Font1,$String,$Width);
else:
$x_offset = ($Width / 2) - ((min($TextDimensions[2],$TextDimensions[4]) - max($TextDimensions[0],$TextDimensions[6])) / 2);
endif;
// Creates drop-shadow
imagettftextblur($Image,$FontSize,$Angle,$x_offset+5,$y_offset+5,$ShadowColor,$Font1,$String,10);
// Creates text over drop-shadow
imagettftextblur($Image,$FontSize,$Angle,$x_offset,$y_offset,$TextColor,$Font1,$String);
else:
if ($CenterAlign === TRUE):
$x_offset = CenterText($FontSize,$Font1,$String,$Width);
else:
$x_offset = ($Width / 2) - ((min($TextDimensions[2],$TextDimensions[4]) - max($TextDimensions[0],$TextDimensions[6])) / 2);
endif;
imagettftext($Image,$FontSize,$Angle,$x_offset,$y_offset,$TextColor,$Font1,$String);
endif;
return imagepng($Image);
imagedestroy($Image);
}
I am calling the function with the code below and note that the "/" is part of the text string but it is also the separation between the fonts and will probably be presenting using the second font:
PHP:
$String = "firsttext / second text";
$Font1 = "racew17.ttf";
$Font2 = "timesbd.ttf";
$Size = 20;
$Angle = 0;
$Shadow = TRUE;
$CenterAlign = TRUE;
echo textimage($String,$Font1,$Font2,$Size,$Angle,$Shadow,$CenterAlign);