Saving barcodes

Include necessary files

Our software fully supports PSR-4 which will autoload all the classes you need if you use Composer.


require __DIR__ . '/vendor/autoload.php';

If you do not use Composer, load each file that you require as such:


require_once('../packages/barcode-common/src/BCGColor.php');
// And other files.

Next, simply include some common classes to use in your file:


use BarcodeBakery\Common\BCGColor;
use BarcodeBakery\Common\BCGDrawing;
use BarcodeBakery\Common\BCGFontFile;
use BarcodeBakery\Common\BCGLabel;

Then, include the barcode type you want to generate. Let's try to generate a Code 128:


use BarcodeBakery\Barcode\BCGcode128;

Generating colors

Before we start generating barcodes, we have to decide which colors we want to use to display our barcode.
Generally, we use black and white bars.


// The arguments are R, G, and B for color.
$colorBlack = new BCGColor(0, 0, 0);
$colorWhite = new BCGColor(255, 255, 255);

Font for Label

We will now create a font for writing a label under the barcode. If you don't wish to have a text label, ignore this step.
The first argument is the path to the TTF font file and the second is the size in points (pt) of the font.


$font = new BCGFontFile(__DIR__ . '/font/Arial.ttf', 18);

Creating the barcode

Now, we will create the barcode. There is no parameter for the class constructor; you must call the provided methods to modify the barcode properties (see the manual). At the end of the code, you must call the function parse() in order to analyze the code you want to draw.


$code = new BCGcode128();
$code->setScale(2); // Resolution
$code->setThickness(30); // Thickness
$code->setForegroundColor($colorBlack); // Color of bars
$code->setBackgroundColor($colorWhite); // Color of spaces
$code->setFont($font); // Font (or 0)
$code->parse('HELLO'); // Text

Saving the barcode to a file

We need to put the barcode on a drawing surface. We will use the BCGDrawing class.
The first argument is the barcode. The last argument is the background color.
To finish, call the Finish method with the argument BCGDrawing::IMG_FORMAT_PNG or BCGDrawing::IMG_FORMAT_JPEG to have a PNG or a JPG file. Then pass in the file name as the second argument.


$drawing = new BCGDrawing($code, $colorWhite);
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG, 'hello.png');