Skip to content

Instantly share code, notes, and snippets.

@grambas
Created Aug 27, 2019
Embed
What would you like to do?
class TextToImage
{
/**
* @param string $text
* @param int $width
* @param int $height
* @param int $font
*
* @return Response
*/
public static function createJpgResponse(string $text, int $width = 360, int $height = 40, int $font = 6): Response
{
$textWidth = imagefontwidth($font) * strlen($text);
$textHeight = imagefontheight($font);
if ($textWidth > $width){
$width = $textWidth + 50;
}
$yPos = ceil(($height / 2) - ($textHeight / 2));
$xPos = ceil(($width / 2) - ($textWidth / 2));
$img = imagecreatetruecolor($width, $height);
$textColor = imagecolorallocate($img, 0, 0, 255);
imagestring($img, $font, $xPos, $yPos, $text, $textColor);
$response = new Response();
$response->headers->set('Content-Type', 'image/jpeg');
$response->sendHeaders();
imagejpeg($img, null, 100);
imagedestroy($img);
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment