Sunday, 17 July 2011

Progress Bar written in PHP using GD and TTF fonts

So I had a need of a progress bar to show the user their progress through a series of pages filling in data. I'm sure I'd seen something similar before but I wanted to do it myself - what's more I wanted to use the type-face that I'd used for the rest of the site.

The following script can be called whatever you want but does require a few parameters in it's calling. The parameters are width, height and percentage. The width and height are the dimension of the required image in px.

It does require that a typeface be discoverable - it might be best to have the typeface in the same directory as the script, at least that works for me. It's a little down and dirty and doesn't do any checking - which is should really, especially for the existance of the correct GD library and the correct parameters etc...

<?php
  $percentage = $_GET['percentage'];
  $width = $_GET['width'];
  $height = $_GET['height'];
  $progress = imagecreate($width, $height);
  imageantialias($my_img, true);
  $black = imagecolorallocate($progress, 0, 0, 0);
  $white = imagecolorallocate($progress, 255, 255, 255);
  $grey = imagecolorallocate($progress, 204, 204, 204);
  $lGrey = imagecolorallocate($progress, 221, 221, 221);
  imagefilledrectangle($progress, 0, 0, $width, $height, $black);
  imagefilledrectangle($progress, 1, 1, ($width - 2), ($height - 2), $white);
  imagefilledrectangle($progress, 1, 1, (($percentage/100) * ($width - 2)), ($height - 2), $grey);
  $text = $percentage." %";
  $font = 'Gothicb.TTF';
  $font_size = 12;
  $text_box = imagettfbbox($font_size, 0, $font, $text);
  $text_width = $text_box[2]-$text_box[0];
  $text_height = $text_box[7]-$text_box[1];
  $x = ($width/2) - ($text_width/2);
  $y = ($height/2) - ($text_height/2);
  imagettftext($progress, 12, 0, ($x + 1), ($y + 1), $lGrey, $font, $text);
  imagettftext($progress, 12, 0, $x, $y, $black, $font, $text);
  header("Content-type: image/png");
  imagepng($progress);
  imagecolordeallocate($black);
  imagecolordeallocate($white);
  imagecolordeallocate($grey);
  imagecolordeallocate($lGrey);
  imagedestroy($progress);
?>

No comments:

Post a Comment