Quick PHP Script to Generate a Barcode

This is a really quick script I came up with to generate a Code-39 Barcode. Many thanks to
Matthew Welch who created the Free 3 of 9 Barcode Font. PHP’s imagettftext function makes this pretty simple.

The $barcode_font referenced below is available from the link above ‘3 of 9’ font. The $plain_font is just a font file that I copied from /usr/share/fonts/default/Type1/ on a Linux box.

This script create a nice looking barcode with the text underneath it like this:

< ?php

$number = isset($_GET['number']) ? $_GET['number'] : '';

$barcode_font = dirname(__FILE__).'/fonts/FREE3OF9.TTF';
$plain_font   = dirname(__FILE__).'/fonts/plain.pfb';

$width = 200;
$height = 80;

$img = imagecreate($width, $height);

// First call to imagecolorallocate is the background color
$white = imagecolorallocate($img, 255, 255, 255);
$black = imagecolorallocate($img, 0, 0, 0);

// Reference for the imagettftext() function
// imagettftext($img, $fontsize, $angle, $xpos, $ypos, $color, $fontfile, $text);
imagettftext($img, 36, 0, 10, 50, $black, $barcode_font, $number);

imagettftext($img, 14, 0, 40, 70, $black, $plain_font, $number);

header('Content-type: image/png');

imagepng($img);
imagedestroy($img);

?>