Tuesday, 2 October 2012

Tagged under: , , ,

Creating a Barcode in PHP

A barcode is an optical machine-readable representation of data relating to the object to which it is attached. Originally barcodes represented data by varying the widths and spacings of parallel lines, and may be referred to as linear or one-dimensional (1D).
A Barcode is generally used to map a product to its characteristics. For example, a barcode is commonly used to identify the product code, and map the unique code to the price of the product in the database. This barcode is a widely used technique.
Creating a barcode is a fairly easy job, provided you have the right font for it. I found one, with relative ease, and guess what....it was free of cost!! I have added the font file in free3of9.zip folder, which can be downloaded from the download box present in the sidebar. I really want to thank the creator of this font, for his hardwork, and also making his work available free of charge.
Once you have the right font, the rest is quite an easy job. we will use the basic function in PHP, viz

imagettftext($img, $fontsize, $angle, $xpos, $ypos, $color, $fontfile, $text);
Now, create a PHP file, which I have named as index.php in my case.

Include the following code in the file:


$number = '*8108137*';

$barcode_font = 'FRE3OF9X.TTF';

$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');


Here, in this code, the code for which barcode needs to be generated is stored in the $number variable. Care needs to be taken that the code starts and ends with an asterisk (*). The barcode scanner starts looking for an asterisk, and then scans ahead of * till it reaches the ending *.
For example, if the code is 1234567, it is represented as *1234567*.
Now, this number, or code can be passed from another page, using the GET method of PHP.
Your code is now ready!! Open your project in localhost, and see your code generating a Barcode!! 

If you found the post helpful, please share!!