Skip to content

Instantly share code, notes, and snippets.

@grambas
Created August 27, 2019 07:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grambas/d08aeca57cc64fd89431a3fc9b32ca34 to your computer and use it in GitHub Desktop.
Save grambas/d08aeca57cc64fd89431a3fc9b32ca34 to your computer and use it in GitHub Desktop.
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