Skip to content

Instantly share code, notes, and snippets.

@joeydsmith
Created November 25, 2014 21:27
Show Gist options
  • Save joeydsmith/91956579fa99d95ff5e1 to your computer and use it in GitHub Desktop.
Save joeydsmith/91956579fa99d95ff5e1 to your computer and use it in GitHub Desktop.
<?php
//content type
header('Content-Type: image/png');
$font = 'znikomit-webfont.ttf';
$font_size = $_GET['s'];
$width = $_GET['w'];
$margin = 5;
$text = $_GET['t'];
//explode text by words
$text_a = explode(' ', $text);
$text_new = '';
foreach($text_a as $word){
//Create a new text, add the word, and calculate the parameters of the text
$box = imagettfbbox($font_size, 0, $font, $text_new.' '.$word);
//if the line fits to the specified width, then add the word with a space, if not then add word with new line
if($box[2] > $width - $margin*2){
$text_new .= "\n".$word;
} else {
$text_new .= " ".$word;
}
}
//trip spaces
$text_new = trim($text_new);
//new text box parameters
$box = imagettfbbox($font_size, 0, $font, $text_new);
//new text height
$height = $box[1] + $font_size + $margin * 2;
//create image
$im = imagecreatetruecolor($width, $height);
//create colors
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
//color image
imagefilledrectangle($im, 0, 0, $width, $height, $white);
//add text to image
imagettftext($im, $font_size, 0, $margin, $font_size+$margin, $black, $font, $text_new);
//return image
imagepng($im);
//frees any memory associated with image
imagedestroy($im);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment