Escaping contact information from spam bots is one of the major challenges developers facing. Converting the text to image and rendering as image is one basic solution. Here is a function I use.
Function to render text as image
<img src="<?php echo render_text_image('test image', 183, 50);?>" />
function render_text_image($string, $width, $height, $text_align_pos = 0)
{
$img = imagecreatetruecolor($width, $height);
$imageX = imagesx($img);
$imageY = imagesy($img);
imagealphablending($img, false);
imagesavealpha($img, true);
$transparent = imagecolorallocatealpha($img, 255,255,255, 127);
$white = imagecolorallocate($img, 129, 78, 16);
$black = imagecolorallocate($img, 0, 0, 0);
$grey = imagecolorallocate($img, 127,127,127);
//imagefilledrectangle($img, 0, 0, $imageX, $imageY, $grey);
imagefilledrectangle($img, 0, 0, $imageX, $imageY, $transparent);
$font = ROOT_DIRECTORY . "assets/font/arialbd.ttf";
//$font = ROOT_DIRECTORY . "assets/font/arialbd.ttf";
$fontSize = 12;
$text = $string;
$textDim = imagettfbbox($fontSize, 0, $font, $text);
$textX = $textDim[2] - $textDim[0];
$textY = $textDim[7] - $textDim[1];
$text_posX = ($text_align_pos== "center") ? ($imageX / 2) - ($textX / 2) : $text_align_pos;
$text_posY = ($imageY / 2) - ($textY / 2);
imagealphablending($img, true);
imagettftext($img, $fontSize, 0, $text_posX, $text_posY, $white, $font, $text);
//ImageString($img,2,0,0, $text,$black);
//Get image to a variable
ob_start();
imagepng($img);
// Capture the output
$imagedata = ob_get_contents();
// Clear the output buffer
ob_end_clean();
return "data:image/png;base64," . base64_encode($imagedata);
}
No comments:
Post a Comment