|
<?php |
|
|
|
/** |
|
* Converts text to png |
|
* |
|
* @author Kevin Andrews <[email protected]> |
|
*/ |
|
class TextToPng |
|
{ |
|
protected $str = ''; |
|
|
|
public function __construct($str = '') |
|
{ |
|
$this->str = $str; |
|
} |
|
|
|
public function getString() |
|
{ |
|
return $this->str; |
|
} |
|
|
|
public function setString($str) |
|
{ |
|
$this->str = $str; |
|
return $this; |
|
} |
|
|
|
public function generate($font='arial.ttf', $fontSize=8, $opaque=false) |
|
{ |
|
/** Font configs */ |
|
$fontsPath = '/path/to/fonts/dir'; |
|
|
|
/** Size calcs */ |
|
$enclosingBox = imagettfbbox(25, 0, $fontsPath . DIRECTORY_SEPARATOR . $font, $this->str); |
|
$width = ($enclosingBox[2] - $enclosingBox[0]) + 10; |
|
$height = ($enclosingBox[1] - $enclosingBox[7]) + $fontSize; |
|
|
|
/** Create a blank image */ |
|
$im = imagecreatetruecolor($width, $height); |
|
imagealphablending($im, false); |
|
imagesavealpha($im, true); |
|
|
|
if(!$im) { |
|
throw new Exception('Missing GD 2 extension.'); |
|
} |
|
|
|
/** Define Colours */ |
|
$transparent = imagecolorallocatealpha($im,255,255,255,127); |
|
$white = imagecolorallocate($im, 255, 255, 255); |
|
$black = imagecolorallocate($im, 0, 0, 0); |
|
|
|
// Fill the entire background |
|
imagefill($im, 0, 0, ($opaque) ? $white : $transparent); |
|
|
|
// Render text to image |
|
imagettftext($im, $fontSize, 0, 5, ($height/2) + ($fontSize/2), $black, $fontsPath . DIRECTORY_SEPARATOR . $font, $this->str); |
|
|
|
// Open stream to varaiable |
|
VariableStream::register(); |
|
$filePointer = fopen('var://tempImage', 'w+'); |
|
|
|
// Output image to stream |
|
imagepng($im, $filePointer); |
|
imagedestroy($im); |
|
|
|
/** seek to the start of the variable stream and read whole raw png back */ |
|
fseek($filePointer, 0, SEEK_SET); |
|
$imageRaw = ''; |
|
while (!feof($filePointer)) { |
|
$imageRaw .= fread($filePointer, 8192); |
|
} |
|
|
|
fclose($filePointer); |
|
} |
|
} |