Generating PHP Barcode Images
I have just been writing some code to generate a barcode image in PHP, which I thought might be useful to others.
Firstly, you will need this free barcode font and to have the GD or GD2 extension installed on your server.
The page takes a value “string” which it converts into an barcode, for example I have been using “string=*00001234*” for my barcode testing. It can also take “width”, “height” and “fontsize” optional parameters.
//set the content type this page returns
Header (”Content-type: image/png”);
//set the default values
$width = 200;
$height = 35;
$fontsize = 35;
$text = ”;
//Get the parameters passed to the page
if(isset($_REQUEST[’width’]))
$width = $_REQUEST[’width’];
if(isset($_REQUEST[’height’]))
$height = $_REQUEST[’height’];
if(isset($_REQUEST[’fontsize’]))
$fontsize = $_REQUEST[’fontsize’];
if(isset($_REQUEST[’string’]))
$text = $_REQUEST[’string’];
//align the barcode at the bottom and one pixel from the left
$startlocation_y = $height;
$startlocation_x = 1;
//create and image of the correct size
$img_handle = imagecreate($width,$height);
//add the black and white colours to the image
$white = imagecolorallocate($img_handle,255,255,255);
$black = imagecolorallocate($img_handle,0,0,0);
//write the barcode text to the image using the “Free 3 of 9 Extended”
//barcode font which must be in the same directory.
//The $black colour is negated to remove anti-aliasing.
//The 0 indicates the angle of the text.
imagettftext($img_handle, $fontsize , 0, $startlocation_x, $startlocation_y, -$black, ‘FRE3OF9X’, $text);
//return the image and release resources
imagepng ($img_handle);
imagedestroy ($img_handle);
?>
