Creating barcodes
| Chapter 27. QR (2D-Barcode) |

## Creating barcodes

In order to use QR codes the module "`QR/qrencoder.inc.php`" must first be included.

Usage of QR codes follows a similar schema as for the linear, PDF417 and Datamatrix barcodes with the concepts of an encoder and backend. The principle of the overall encodation process is shown in Figure 26.4. Datamatrix encodation principle

Figure 27.5. QR Encodation Process

### Getting started

In order to use the QR barcodes the library module "`QR/qrencoder.inc.php`" must first be included in the script.

1. Create an instance of the encoder and optionally specify size and error correction level. The encoder is created as an instance of `class QREncoder`

2. Create an instance of a suitable backend for the chosen output format (image or postscript) by calling the `DatamatrixBackenFactory::Create()`

3. Encode data and send it back to the browser or to a file with a call to the backend `Backend::Stroke()` method.

The following script shows how to create the simplest possible QR code (in PNG format) representing the data string "`The first QR code`" encoded using all default values. The resulting QR Code is shown in Figure 27.6. The first very basic QR code `(`qrexample00.php`)`

Example 27.1. The first very basic QR code (`qrexample00.php`)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    <?php
    require_once ('jpgraph/QR/qrencoder.inc.php');

    // Data to be encoded
    $data = '01234567';

    // Create a new instance of the encoder and let the library
    // decide a suitable QR version and error level
    $e=new QREncoder();

    // Use the image backend (this is also the default)
    $b=QRCodeBackendFactory::Create($e);

    // .. send the barcode back to the browser for the data
    $b->Stroke($data);
    ?>

Figure 27.6. The first very basic QR code `(`qrexample00.php`)`

(As can be seen this follows the same principles as the creation of Datamatrix symbols)

The principle is the same for all type of data QR code creations. First an instance of the chosen encoder is instantiated. In this case using all default parameters by creating an instance of `class QREncoder`. We then create a suitable backend that handles the output of the barcode. By default the output will be an image encoded in the PNG image format.

The final step is to send back the generated image to the browser with a call to the method `Backend::Stroke()` with the data to be encoded as its first argument.

The example above does not have any error handling. If there is some error in the process an exception will be thrown in the same way as in other places in the library. The default exception will display a standard library image error box. An example of this is shown in Figure 27.7. QR Error message

Figure 27.7. QR Error message

If some additional processing is necessary and to just display a text based re-formatted error message we could change the above code to catch this exception as the following example shows.

Example 27.2. Adding basic exception handling (`qrexample0.php`)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    <?php
    require_once ('jpgraph/QR/qrencoder.inc.php');

    // Data to be encoded
    $data = '01234567';

    // Create a new instance of the encoder and let the library
    // decide a suitable QR version and error level
    $encoder = new QREncoder(1);

    // Use the image backend (this is also the default)
    $backend = QRCodeBackendFactory::Create($encoder);

    try {
        //     . send the QR Code back to the browser
        $backend->Stroke($data);
    } catch (Exception $e) {
        $errstr = $e->GetMessage();
        echo 'QR Code error: '.$e->GetMessage()."\n";
        exit(1);
    }

    ?>

Figure 27.8. Adding basic exception handling `(`qrexample0.php`)`

As a final initial example the next script uses the backend method `Backend::SetModuleWidth($aWidth)` to increase the size of one module. Since a module in QR code refers to the smallest square used adjusting the module width will also adjust the height of the overall QR code

Example 27.3. Adjusting the module width for the QR code (`qrexample01.php`)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    <?php
    require_once ('jpgraph/QR/qrencoder.inc.php');

    // Data to be encoded
    $data = '01234567';

    // Create a new instance of the encoder and let the library
    // decide a suitable QR version and error level
    $encoder = new QREncoder();

    // Use the image backend
    $backend = QRCodeBackendFactory::Create($encoder, BACKEND_IMAGE);

    // Set the module size (quite big)
    $backend->SetModuleWidth(5);

    // .. send the barcode back to the browser for the data
    $backend->Stroke($data);
    ?>

Figure 27.9. Adjusting the module width for the QR code `(`qrexample01.php`)`

### Error handling

As in other parts of the library the QR module throws an exception when an error occurs. As shown in the previous section an error image is the default if no explicit `try {} catch {}` statement is added to the script.

### Note

The fact that an image is shown as the default exception is caused by the library module "qrexception.inc.php" installing its own default error handler which will be called when an exception happens. However, this handler is intelligent enough to know if the exception is caused by the library or not. If the exception is not caused by the library the exception is re-thrown and the original error handler restored. This means that JpGraph will not interfere with previously installed error handlers for other parts of an application.

The script below shows how to catch the error, do some possible clean up and then explicitly create and send back the error image.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <?php
    ...
    try {
        $backend->Stroke($data);
    } catch( Exception $e ) {
        doCleanup();
        $errobj = new QRErrObjectImg();
        $errobj->Raise($e->getMessage());
    }
    ?>

another variant of this would be to re-throw the exception after the cleanup has been performed as the following example shows

    1
    2
    3
    4
    5
    6
    7
    8
    9
    <?php
    ...
    try {
        $backend->Stroke($data);
    } catch( Exception $e ) {
        doCleanup();
        throw $e;
    }
    ?>

It is also possible to get hold of the internal error code that corresponds to each error message by calling the PHP standard exception method `Exception::getCode()` as the following example shows

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <?php
    ...
    try {
        $backend->Stroke($data);
    } catch (Exception $e) {
        $errstr = $e->GetMessage();
        $errcode = $e->GetCode();
        echo "QR error ($errcode). Message: $errstr\n";
    }
    ?>

Table 27.4. QR Error messages lists the public errors that can be thrown by the QR code module (the table deliberately excludes internal error messages)

Table 27.4. QR Error messages

Error number | Error string
--- | ---
1000 | Tilde processing is not yet supported for QR Barcodes.
1001 | Inverting the bit pattern is not supported for QR Barcodes.
1002 | Cannot read data from file %s
1003 | Cannot open file %s
1004 | Cannot write QR barcode to file %s
1005 | Unsupported image format selected. Check your GD installation
1006 | Cannot set the selected barcode colors. Check your GD installation and spelling of color name
1007 | QR Error: HTTP headers have already been sent. Caused by output from file %s at line %d Explanation: HTTP headers have already been sent back to the browser indicating the data as text before the library got a chance to send it's image HTTP header to this browser. This makes it impossible for the QR library to send back image data to the browser (since that would be interpretated as text by the browser and show up as junk text). Most likely you have some text in your script before the call to QRBackend::Stroke(). If this texts gets sent back to the browser the browser will assume that all data is plain text. Look for any text (even spaces and newlines) that might have been sent back to the browser. For example it is a common mistake to leave a blank line before the opening "<?php"
1008 | Could not create the barcode image with image format=%s. Check your GD/PHP installation.
1009 | Cannot open log file %s for writing.
1010 | Cannot write log info to log file %s.
1011 | Could not write the QR Code to file. Check the file system permissions.
1400 | QR Version must be specified as a value in the range [1,40] got %d
1401 | Input data to barcode can not be empty.
1402 | Automatic encodation mode was specified but input data looks like specification for manual encodation.
1403 | Was expecting an array of arrays as input data for manual encoding.
1404 | Each input data array element must consist of two entries. Element $i has of $nn entries
1405 | Each input data array element must consist of two entries with first entry being the encodation constant and the second element the data string. Element %d is incorrect in this respect.
1406 | Was expecting either a string or an array as input data
1407 | Manual encodation mode was specified but input data looks like specification for automatic encodation.
1408 | Input data too large to fit into one QR Symbol
1409 | The selected symbol version %d is too small to fit the specified data and selected error correction level.
1410 | Trying to read past the last available codeword in block split.
1415 | Manually specified encodation schema MODE_NUMERIC has no data that can be encoded using this schema.
1416 | Manually specified encodation schema MODE_ALPHANUM has no data that can be encoded using this schema.
1417 | Manually specified encodation schema MODE_BYTE has no data that can be encoded using this schema.
1418 | Unsupported encodation schema specified (%d)
1419 | Found character in data stream that cannot be encoded with the selected manual encodation mode.
1420 | Encodation using KANJI mode not yet supported.
1422 | Found unknown characters in the data stream that can't be encoded with any available encodation mode.
1423 | Kanji character set not yet supported.
1427 | Expected either DIGIT, ALNUM or BYTE but found ASCII code=%d

### Creating an encoder

A QR encoder is created as an instance of `class QREncoder`. The constructor have the following signature

- `QREncoder::__construct($aVersion = -1, $aErrLevel = QRCapacity::ErrM)`

  `$aVersion`, Specifies the QR version and is specified as an integer in the range [1,40], see Table 27.2. Maximum data capacity for the different symbol sizes in the QR-code.

  `$aErrLevel`, Specifies the error correction level to be used, see Table 27.3. QR Error correction levels

The following examples creates a basic encoder which will automatically select the smallest possible size to fit the data given

    1
    $encoder = new QREncoder();

The following example will create an instance of an encoder with size 22 and error correction level 'Q'

    1
    $encoder = new QREncoder(22, QRCapacity::ErrQ);

### Encodation of input data options

The absolute simplest way of encoding data is simply to create a simple string representing the data to be encoded and then pass that string as the first argument to the `Stroke()` method in the backend. The encoder will then analyze the input data and choose the most efficient space saving encoding schema for this data.

### Note

Unless there are some really good reasons to use manual encodation it should be left to the library to determine this in an optimal way!

The QR standard allows 3 different compaction schema that can be used to minimize the number of codewords used for a particular data string. This also means that a particular data string may have several different valid barcodes that visually looks different.

The supported compaction modes in the library are:

- Alpha compaction mode Efficient encoding of digits 0 - 9; upper case letters A -Z and nine other characters: space, $ % * + - . / : .

- Numeric compaction mode. Efficient encoding of numeric data. For long consecutive strings of digits this gives a better compaction than the alpha mode.

- Byte compaction mode. Used only when there is a need to encode byte values as is, i.e. values in the range 0-255. Please note that some barcode readers, especially those with a keyboard wedge, don't send back the proper encoding for ASCII values lower than 32 or higher than 126.

When the automatic encoding is chosen this will create an optimum encoding (from a size perspective) of the supplied data. This includes shifting encoding method in the middle of the data one or several time depending on the structure of the data.

It is also possible to manually control the exact encodation of the input data. This is done by supplying one or more data tuples where the first entry in the tuple is the compaction schema and the second the data. To encode the data manually the following structure must then be followed:

Figure 27.10. Structure for manually specify QR encodation schema

    $data = array( array( <encoding_mode1> , <data1> ),
                   array( <encoding_mode2> , <data2> ),
                             ...
                   array( <encoding_modeN> , <dataN> ));

The encoding mode is specified as one of three symbolic constants

- `QREncoder::MODE_NUMERIC`

- `QREncoder::MODE_ALPHANUM`

- `QREncoder::MODE_BYTE`

and the data is specified as a regular text string. Each section of data must therefore have the compaction mode specified.

In order to use a specific encodation schema one has to create an array as input instead of the normal string input. For example, to specify an input where the encodation should be alphanumeric encoding of the digits '0123456789' one would have to create the array

    1
    2
    3
    4
    5
    <?php
    $data = array( array( QREncoder::MODE_ALPHANUM,'0123456789') );
    ...
    $backend->Stroke($data)
    ?>

It is also possible to use different encodings for different parts of the data in a similar way as the following example shows

    1
    2
    3
    4
    5
    6
    7
    8
    <?php
    $data = array( array(QREncoder::MODE_ALPHANUM,'0123456789'),
                   array(QREncoder::MODE_BYTE,'ABCDEFGH')
                 );
    ...
    ...
    $backend->Stroke($data)
    ?>

### Reading input data from a file

Normally the method Backend::Stroke($aData) is sued to create a QR code from the datastring given. This string can of course come from a database, user input or from a file. The library provides a utility method

- `Backend::StrokeFromFile($aFromFile,$aToFile='')`

  `$aFromFile`, The file to read the data from

  `$aToFile`, Optional filename to write the generated QR code to

which makes it easy to get data directly from a file. Otherwise it behaves exactly the same as the normal `Backend::Stroke()`.

### Creating different backends

In order to create the actual output one or more backends must be created. The QR Code supports the following backends:

- `BACKEND_IMAGE`, Create an image backend. This is the default backend if no explicit backend is specified.

- `BACKEND_PS`, Create a postscript backend. The text string that represents the postscript for the barcode is returned directly from the `Backend::Stroke()`

- `BACKEND_EPS`, Create an encapsulated postscript backend

- `BACKEND_ASCII`, This is a special backend which will generate an ASCII rendering of the datamatrix barcode. This is mostly practical for technical investigations regarding the technical structure of a Datamatrix barcode.

The following code snippet shows two ways of creating a barcode image backend.

    1
    2
    3
    4
    5
    <?php
    $encoder = new QREncoder();
    $backend = QRCodeBackendFactory::Create($encoder);
    ...
    ?>

    1
    2
    3
    4
    5
    <?php
    $encoder = new QREncoder();
    $backend = QRCodeBackendFactory::Create($encoder,BACKEND_IMAGE);
    ...
    ?>

The following code shows a complete script to generate a postscript output

Example 27.4. Generating Postscript output (`qrexample11.php`)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    <?php
    // Include the library
    require_once ('jpgraph/QR/qrencoder.inc.php');

    // Example 11 : Generate postscript output

    $data         = 'ABCDEFGH01234567'; // Data to be encoded
    $version      = -1;  // -1 = Let the library decide version (same as default)
    $corrlevel    = QRCapacity::ErrH; // Error correction level H (Highest possible)
    $modulewidth  = 3;

    // Create a new instance of the encoder using the specified
    // QR version and error correction
    $encoder = new QREncoder($version,$corrlevel);

    // Use the image backend
    $backend = QRCodeBackendFactory::Create($encoder, BACKEND_PS);

    // Set the module size
    $backend->SetModuleWidth($modulewidth);

    // Store the barcode in the specifed file
    $ps_str = $backend->Stroke($data);

    echo '<pre>'.$ps_str.'</pre>';
    ?>

Figure 27.11. QR Code - Example Postscript Output

### Generic backend methods

The following methods are available to adjust the final look and feel of the barcode

1. `Backend::SetColor($aOne, $aZero, $aBackground='white')`

   the color of the 'black' and 'white' modules in the barcode and the quiet area around the barcode

2. `Backend::SetQuietZone($aSize)`

   the size of the "quiet zone" in pixels for the image backend and in points (1 pt = 1/72 inch) for the postscript backend

3. `Backend::SetModuleWidth($aWidth)`

   the module width specified in pixels for the image backend and in points (1 pt = 1/72 inch) for the postscript backend

4. `Backend::Stroke($aData, $aFileName='')`

   create the barcode and send it back the client or store it to a file if the second parameter is set. For postscript backends the postscript string is returned directly from the method. (See example above)

5. `Backend::StrokeFromFile($aFromFileName,$aFileName='')`

   This allows the creation of barcode directly from data in a file.

### Image backend methods

For the image backend it is possible to adjust the image encoding format with the following method

1. `Backend::SetImgFormat($aFormat,$aQuality=75)`

   Specify image format. Possible values are

   - `'auto'`

   - `'png'`

   - `'jpeg'`

   - `'gif'`

   For 'jpeg' format the quality parameter is a number in range [1-100] and specified how much compression / (Data loss) should be used. 100=no compression. Normal values are in the range [60-95]

   The following example sets the image format to 'JPEG' with quality 80.

       1
       $backend->SetImgFormat('jpeg', 80);

### Postscript backend methods

For postscript backend it is possible to select whether the postscript should be generated as encapsulated postscript. This is controlled by the method

- `Backend::SetEPS($aFlg=true)`

### A template to create barcodes

The following (complete) script can be used as a starting point for creation of more advanced barcode scripts

Example 27.5. A QR code template (`qr_template.php`)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    <?php
    require_once ('jpgraph/QR/qrencoder.inc.php');

    // Data to be encoded
    $data         = 'ABCDEFGH01234567';

    // QR Code specification
    $version      = -1;                  // -1 = Let the library decide version (same as default)
    $corrlevel    = QRCapacity::ErrM;   // Medium erro correction
    $modulewidth  = 2;                    // Module width
    $back         = BACKEND_IMAGE;        // Default backend
    $quiet          = 4;                     // Same as default value

    // Create encoder and backend
    $encoder = new QREncoder($version, $corrlevel);
    $backend = QRCodeBackendFactory::Create($encoder, $back);

    // Set the module size
    $backend->SetModuleWidth($modulewidth);

    // Set Quiet zone (this should rarely need changing from the default)
    $backend->SetQuietZone($quiet);

    if( $back == BACKEND_IMAGE ) {

        $backend->Stroke($data);
    }
    else {
        $str = $backend->Stroke($data);
        echo '<pre>'.$str.'</pre>';
    }
    ?>

Figure 27.12. A QR code template `(`qr_template.php`)`

### Sample application

As an example the library includes a WEB-based demo barcode creation application. This application can be used to easily create barcode through it's WEB interface. It is available at '`qr/demoapp/index.html`'

This application is primarily included as a demo on the features available in the library and not as a finalized product.

Figure 27.13. QR Code WEB-based demo application shows a screen shot of the application interface.

Figure 27.13. QR Code WEB-based demo application

| Up |
| Home |