Dynamic Buttons with GD and PHP
By Flib
2009-05-20
Category: PHP
The Problem
On many sites its very difficult to predict exactly which graphics you might need. One answer is dynamic buttons.
The Solution
Dynamic Buttons
<?php
require_once('./lib/config.php');
require_once('./lib/stdinc.php');
$w=120;
$h=20;
$left=TRUE;
$right=TRUE;
$selected=FALSE;
$drawtext=TRUE;
$fontdir='./images/';
//$font='SERPNTB.TTF';
$font='INC901N.TTF';
$fontsize=11;
$texty=15;
$scale=FALSE;
$bgfile='./images/buttonbarbg5.png';
if (isset($_REQUEST['l'])) $left=FALSE;
if (isset($_REQUEST['r'])) $right=FALSE;
if (isset($_REQUEST['w'])) $w=$_REQUEST['w'];
if (isset($_REQUEST['h'])) $h=$_REQUEST['h'];
if (isset($_REQUEST['sel'])) $selected=TRUE;
if (isset($_REQUEST['sc'])) $scale=TRUE;
$text=(isset($_REQUEST['text']))?$_REQUEST['text']:'';
if ($text=='') $drawtext=FALSE;
if (($text=='') and (!isset($w))) $w=100;
$textbbox=imagettfbbox($fontsize,0,$fontdir.$font,$text);
$textwidth=$textbbox[2]-$textbbox[0];
if (!isset($w)) $w=$textwidth+30;
$textx=round(($w/2)-($textwidth/2));
$bgimg=imagecreatefrompng($bgfile);
$gd=imagecreate($w,$h);
if ($scale) {
imagecopyresampled($gd,$bgimg,0,0,0,0,$w,$h,imagesx($bgimg),imagesy($bgimg));
} else {
imagecopyresampled($gd,$bgimg,0,0,0,0,$w,$h,$w,$h);
}
$wht=imagecolorallocate($gd,255,255,255);
$lowlight=imagecolorallocate($gd,0,0,0); //lowlight
$highlight=imagecolorallocate($gd,120,120,200); //highlight
$bg=imagecolorallocate($gd,32,32,128);
if ($selected) {
$bg=imagecolorallocate($gd,255,255,255);
}
if ($right) {
imageline($gd,0,0,0,$h-1,$lowlight);
}
if ($left) {
imageline($gd,1,0,1,$h-1,$highlight);
}
if($selected) {
$texty+=2;
}
if ($drawtext) {
imagettftext($gd,$fontsize,0,$textx+1,$texty+1,$lowlight,$fontdir.$font,$text);
imagettftext($gd,$fontsize,0,$textx,$texty,$wht,$fontdir.$font,$text);
}
header('Content-type: image/png');
header('Expires: 120');
imagepng($gd);
imagedestroy($gd);
imagedestroy($bgimg);
?>
The code isn't very complex, but allows dynamic generation of a few different versions of a standard button.
The arguments to the script are as follows
- text - The text to appear on the button
- l - If set, the left highlight is omited from the button
- r - If set, the left highlight is omited from the button
- w - The width of the button (overrides the defaults)
- h - The height of the button (overrides the default)
- selected - If set, the text on the button is moved up a small amount to give a rollover effect.
- sc - If set, background image is scaled to fit the button, otherwise it is just copied.