Skip to content

Instantly share code, notes, and snippets.

@bayleedev
Created September 6, 2012 19:44
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 bayleedev/3659846 to your computer and use it in GitHub Desktop.
Save bayleedev/3659846 to your computer and use it in GitHub Desktop.
Align text in PHP GD
<?php
function textSize($size, $angle, $font, $text) {
$f = imagettfbbox($size, $angle, $font, $text);
return array(
'height' => $f[1] - $f[5],
'width' => $f[4] - $f[0]
);
}
function text(&$im, $size, $angle, $y, $color, $font, $text, $align) {
// Image/text sizes
$imageSize = array(
'height' => imagesy($im),
'width' => imagesx($im)
);
$textSize = textSize($size, $angle, $font, $text);
// Starting $x position
switch(strtoupper($align)) {
case 'R':
$x = $imageSize['width'] - $textSize['width'];
break;
case 'C':
$x = ($imageSize['width'] - $textSize['width']) / 2;
break;
default:
$x = 0; // L
}
// Render
imagettftext($im, $size, $angle, $x, $y, $color, $font, $text);
return;
}
// Create a 300x150 image
$im = imagecreatetruecolor(300, 150);
// Colors
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);
// Create black border
imagefilledrectangle($im, 1, 1, 297, 147, $white);
// Path to our font file
$font = './Arial.ttf';
// Write it
text($im, 10, 0, 30, $black, $font, $_GET['q'], 'c');
// Output to browser
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment