Overview
RMaxiCode for PHP is a software package that allows you to create MaxiCode
symbols.
MaxiCode is a two-dimensional (2D) matrix symbology originally created by United
Parcel Service (UPS) for a fast sorting of packages. It's a square of a fixed
size of one inch per side that contains a number of hexagonal modules arranged
around a 'finder' pattern in the center, made of three concentric circles (bullseye).
It can be use in several modes, modes 2 & 3 are used for transport applications
and encode three mandatory fields ( postal code, country & service class)
plus free data. Modes 4 & 5 are of general purpose so any kind of data can
be encoded. Depending on the mode and the kind of data to be encoded, one MaxiCode
symbol may contain up to 93 alphanumeric characters, or up to 138 digits. Any
8 bit ASCII character can be encoded. Capacity can be increased by using up
to 8 symbols that conform a set called 'Structured Append'.
For more information on MaxiCode symbology, visit maxicode.com.
RMaxiCode for PHP implements:
- Modes 2 to 6 (all currently in use)
- Any printer resolution
- Capacity optimization algorithm
- The Structured Append.
Some of its main features are:
- You have control over many relevant parameters in order to customize the
symbol to your particular needs :
- You can define a quite zone greater than the mandatory one.
- You can specify the background color, and the color of the modules.
- You can rotate the image 90,180 or 270 degrees.
- The resulting image can be sent directly to the browser or to a file, in
several formats (PNG, JPEG, GIF, WBMP).
- Developed using object oriented programing techniques, you can easily modify
the source code to adapt it to your specific application needs if you ever
need to (of course you can also count on us to do it).
Requirements
- A working PHP4 or PHP5 system
- GD library. It's usually bundled into PHP.
- Support for specific image formats such as GIF or JPEG if you want to use
them. Default is PNG. In recent PHP versions you will likely have at least
PNG and JPEG.
Installation
Create a working directory for the application. It should be OUTSIDE the web
server tree (this is, the web server should not access it). We will call it
"the application directory".
Uncompress the provided distribution file into the application directory.
Create another working directory INSIDE the web server tree, and configure
your web server to process PHP files in it. This is, make sure you can access
this directory using an appropriate URL from your browser, make sure that files
with .php extension are parsed through the PHP interpreter, etc. We will call
it "the web directory".
Copy the demo.php file from the application directory to the web directory.
Edit the demo.php in the web directory and update the include_path setting
to the "inc" subdirectory of the application directory. The sentence is at the
beginning of the script. Example :
ini_set("include_path", "/home/myusername/RMaxiCodephp_application/inc" );
Call demo.php using the appropriate URL in your browser and verify it works
properly.
Basic Operation
Generating your first MaxiCode symbol.
You can see an example of the minimum coding effort to get up and running by
using the provided sample code sample.php.
We reproduce and comment it here to show how it works.
First we set the include_path so PHP will find RMaxiCode program files, as
we already did for the demo.php file:
ini_set("include_path", "/home/myusername/RMaxiCodephp_application/inc" );
We charge the class file of RMaxiCode for PHP:
require("MaxiCode_class.inc");
RMaxiCode for PHP uses PHP OOP capabilities in a Java-like style, so prior
of executing
any function we must create a barcode object of the proper type. We use the
$bc- variable for this.
$bc = new MaxiCode();
We are ready to obtain our barcode graphic. However we will usually wish to
specify some parameters. All these settings are optional and if you don’t
call the setting functions the program will use its default values. In this
example we set the MaxiCode mode to 5.
$bc->setMode(5);
To show the symbol, we call the paint() function. It receives as parameter
the character string containing the data to be encoded.
$bc->paint( "string to be encoded" );
If you want the image to be stored into a file or you want to create several images
at a time, see the multisample.php script and the output to file section below.
User functions overview
All functions useful for normal operation of the software are listed below,
grouped by section. Each section explains the use of the related functions,
click on the section title to go to a section.
Generic Image Parameters:
setQuiteZone()
setTopMargin()
setLeftMargin()
setBGColor()
setBarColor()
setRotation()
setImageType()
MaxiCode parameters
setMode()
setProcessTilde()
setPostalCode()
setCountry()
setServiceClass()
setNumberOfSymbols()
setSALayout()
|
|
Creating the symbol image
setFilePath() paint()
Printing
setResolution()
setBrowserDPI()
getImgTagWidth() getImgTagHeight() getImgTag()
Error Management
setErrorShowMode()
setErrorLogMode()
getErrorCode() getErrorMsg()
|
Generic Image Parameters
setQuiteZone( int ) Sets the margin in pixels of the four sides around
the graphic. You can also use setTopMargin() & setLeftMargin() instead.
The MaxiCode specification already requires a quite zone of a defined size.
This mandatory quite zone is always included. By using setQuiteZone() you only
increase the mandatory quite zone with additional space.
setTopMargin( int ) Sets the vertical margin or empty space between
the image’s border and the start of the bars. The bottom margin is set
to the same size.
setLeftMargin( int ) Sets the horizontal margin or empty space between
the image’s border and the start of the bars. The right margin is set
to the same size.
setBGColor( string ) Sets the image’s background color.
It can have two formats :
- A descriptive name among the predefined ones. They are: WHITE, RED, GREEN,
BLUE, YELLOW, CYAN, ORANGE, GRAY, BLACK.
( Note: you may add your own colors editing the source code of Graphics.inc.
Just add them to the $stdColors array definition )
- The color’s RGB values in a comma-separated string.
Examples:
$bc->setBGColor( “YELLOW” ); $bc->setBGColor( “255,128,255” ); // rose
setBarColor( string ) Sets the color of the hexagonal modules &
finder pattern. Same format than setBGColor()
setRotation( integer ) Sets the rotation of the symbol. Acceptable values
are :
- 0 normal
- 90 ( vertical, rotated counterclockwise)
- 180 ( inverted )
- 270 ( vertical, rotated clockwise)
setImageType( string [, integer] ):
Sets the image type in which the graphic will be generated. Second parameter
is the quality (%). It’s optional and should be used only for JPEG.
There are four possible image formats in which the barcode can be generated:
- PNG: default and recommended format
- JPEG: note that image size will be much higher. You can reduce it reducing
image quality ( second optional parameter in setImageType() ).
- GIF: note that it was removed from some GD versions so maybe it's not available
in your system.
- WBMP: note that this is a wireless format so it won’t show on most
browsers
Examples:
$bc->setImageType( “GIF” ); $bc->setImageType( “JPEG”, 50 );
MaxiCode parameters
MaxiCode mode
setMode( int ) Sets the MaxiCode mode. Acceptable values are 2 to 6.
Modes 2&3 require that the postal code, country and service class to be
set. See "Structured Carrier Message" below to learn how to use modes
2&3.
Special Characters
void setProcessTilde( bool ) Enables / disables tilde processing used
for encoding special characters. By default is enabled.
The "~" character (tilde) can be used to introduce special characters
in the input data to be encoded. The format is "~999" where 999 is
a 3-digit number from 0 to 255, this is, an 8 bits character.
Let's suppose you want to encode ABC plus the escape character (ASCII 27).
You could call :
$bc->paint("ABC~027");
This feature is particularly useful when you obtain the data from a form or
other source that may not recognize some special characters. Note that you can
always include any special character from PHP by using the chr() function. Example
:
$bc->paint( "ABC".chr(27) );
Structured Carrier Message
setPostalCode( int or string )
setCountry( int )
setServiceClass( int )
Set the parameters for modes 2&3.
Modes 2 & 3 are reserved for use as a destination sortation symbol for
use by carriers in the transportation industry. In modes 2 & 3 the MaxiCode
symbol contains the "Structured Carrier Message" which consists of
three data fields arranged in a particular format inside the symbol. They are
- Postal Code, which can be numeric (mode 2) or alphanumeric (mode 3). In
case an alphanumeric code is issued for mode 2, RMaxiCode for PHP will automaticament
switch to mode 3.
- Country Code. ISO 3166 code (three digits)
- Service Class. Three digits.
These three parameters can be provided in two ways:
- by using the functions setPostalCode(), setCountry() and setServiceClass()
- by including them in a special message format which is passed to the paint()
function.
In the later case there are two options :
[)>{RS}01{GS}yy{postal code}{GS}{service class}{GS}{country code}{GS}{optional
message}{EOT}
or just:
{postal code}{GS}{service class}{GS}{country code}{GS}{optional message}{EOT}
conventions used:
- {} are used to indicate fields and special characters
- [)> and 01 stand for themselves
- yy is the year in two-digit format
- RS, GS and EOT are the ASCII control characters ( decimal values 30,29 and
4 )
Examples of use :
$bc->setPostalCode( 98765 );
$bc->setServiceClass( 44 );
$bc->setCountry( 123 );
$bc->paint('888 Sesame Street');
or :
$bc->paint( '[)>~03001~0290598765~02944~029123~029888 Sesame Street~004')
or:
$bc->paint( '[98765~02944~029123~029888 Sesame Street~004')
Structured Append
setNumberOfSymbols( int ) sets the maximum number of symbols to use.
Acceptable values are 1 to 8. Default is 8.
setSALayout( string ) sets the symbols layout. There are four possibilities:
'LR' (default,left to right), 'RL' (right to left), 'TB' (top to bottom) and
'BT' (bottom to top).
The 'Structured Append' feature allows to use up to 8 MaxiCode symbols as a
way to increase the encoding capacity. It 's enabled by default so as much symbols
as needed will be created depending on the size of the data to encode. Use setNumberOfSymbols()
to reduce the maximum of symbols that may be used. To disable this feature,
set it to 1.
If more than one symbol is used, they are placed together in a single image.
By default they are arranged horizontally from left to right, but you can arrange
them in three other ways by using setSALayout().
Example of use: allow up to three symbols arranged vertically :
$bc->setNumberOfSymbols(3);
$bc->setSALayout('TB');
Creating the symbol image
Related functions
setFilePath( string ) Sets the file path where the image files will
be created. After calling to this function, subsequent calls to paint() will
create a file instead of sending the image to the browser.
Mixed paint( string [, string] ) Creates and eventually outputs the
symbol image.
Parameters :
- data string to be encoded. In modes 2 or 3 it may contain several fields in
a particular format or just an optional message. See Structured
Carrier Message for details.
- file name to be used (optional)
Returns :
- NULL if some error condition is found that prevents the image to be created.
See Error Management.
- The file name in which the image has been stored (if output is sent to a file).
- An empty string if the image was sent to the browser.
Output to browser
By default, if you don't call to setFilePath(), the paint() function will directly
output the image to the browser (after appropriate HTTP headers of course).
Note that you will usually need an HTML page with a form in it that will set
the appropriate parameters. In the example we provide this is done by demo.php.
In this mode you will usually generate only one image at a time.
Output to file
Activation
Barcode images can be stored into files. To do so you must first call setFilePath()
in order to specify a base directory in your filesystem where the generated
files will be stored. Please end it with a slash (“/”). If you want
to use the current directory use “./” as path (in Windows systems
you can use regular slash as PHP converts it to the backslash ). Note that this
call is mandatory as it also works as an indicator that you want the output
to a file.
File names
You have two options for the file name the generated image will have: You can
pass the file name you wish as a second optional parameter to the paint() method,
or, if you omit it the program will create one.
Multiple file generation
When you send the output to a file, you can easily create many barcode images
in one program call. Just call to the paint() method as many times as you wish.
Printing
Unlike other symbologies, MaxiCode has a fixed size. Its size, about one squared
inch (1 inch = 25,5 mm), is relatively small for the amount of data it includes.
Also, while other symbologies are made of squares or bars, MaxiCode it's made
up of hexagon modules and several circles. Both factors force us to pay special
attention to how the symbol gets printed so it keeps the correct size and has
good quality. Even more, if the symbol is included in a web page that will be
printed directly from an Internet browser, there are some issues that we must
address.
Printing Resolution
bool setResolution( int ) Sets the printer resolution in dots-per-inch
in which the symbol is to be printed. Acceptable values are between 200 and
1200. It is recommended to use a multiple of 100 value. Default is 300dpi.
Note that, when viewed on the computer screen, the image you obtain is of a
size proportional to the selected resolution. When you print it, the printer
should use the same resolution so the printed size is the correct one.
Printing from an Internet browser
Recent Internet browsers for Windows print at a 96 dpi resolution (printing
at 100% of size). This is too low, as the minimum resolution for a MaxiCode
symbol is 200 dpi. However there is a workaround for this: we can use an image
intended for a higher resolution, this is, bigger, but reduce its size in the
HTML "img" tag to the size that it should have at 96 dpi. For instance,
let's suppose we use this img tag :
<img src="oneinch.png" width="96" height="96" />
Let's suppose that oneinch.png is 300x300 pixels of size and that our printer
prints at 300 dpi. The browser will show on screen the image reduced to 96x96
pixels, thus with less quality. However when printing the HTML page, the image
will be printed at 300 dpi, this is, without quality loss and with a size of
one inch.
RMaxiCode for PHP makes some slight adjustments on the image size in order
to try that this mechanism to work optimally. These adjustments are just an
increase of few pixels on the quite zone which do no harm but allow to print
the symbol from a browser at the desired resolution.
Browser printing resolution / Disable optimization.
setBrowserDPI( int ) Sets the browser printing resolution in dots-per-inch.
Default is 96dpi. This value is used for image size optimization. To disable
size adjustments, set it to zero.
We have verified that three recent browsers for Windows ( Opera 7, Firefox
1.0, Internet Explorer 6.0 ) assume images are sized at 96 dpi for printing.
Another probable value is 72 dpi, which seems to be used on Mac OS.
HTML Image Tag
string getImgTag( [string] ) returns an HTML "img" tag with
the best values of width and height for that last image created by calling paint().
The optional parameter is the "src=" path for the image. If you output
the image to a file and you omit this parameter, the path to the image will
be automatically set assuming it is relative to the current web directory.
int getImgTagWidth()
int getImgTagHeight()
You can use these two functions instead of setImgTag() if you prefer to code
yourself the HTML for the "img" tag.
Example
You can see a working example of this mechanism in the included sample script
multisample.php.
Optimization checklist
For this mechanism to effectively work as intended, the following conditions
must be met
- Browser printing resolution is 96dpi, otherwise call setBrowserDPI() with
proper value.
- Before calling to paint(), you call setResolution() with the resolution
the printer is going to use.
- After calling paint(), when showing the image, you use either the HTML provided
by getImgTag() or the sizes provided by getImgTagWidth() and getImgTagHeight().
- You print from the browser at 100% of size.
Error Management
When trying to create the MaxiCode symbol (paint() function) a number of issues
may arise. They have been classified in three categories, similar to those of
PHP : errors, warnings and notices. Errors are serious problems that prevent
the image from being created, warnings indicate non fatal problems -the image
can be created anyway- but they should corrected as they may lead to problems
when decoding. Finally notices are used to inform of minor issues which are
usually irrelevant.
Notes:
- Unless otherwise specified by the context, we will refer generically as
"errors" for the three conditions: errors, warnings or notices.
- Errors are triggered mainly by paint(). In general, functions that set parameters
will ignore wrong parameters and will use defaults instead.
There are three ways errors/warnings/notices can be managed :
- they can be processed by your PHP script
- they can be shown to the user
- they can be logged
The three options are independent and either of them can be used or not used/disabled.
Processing errors in the calling script
string getErrorCode()
string getErrorMsg()
These functions return an error code and description of the last error occurred.
The first character of the error code indicates the type of error: "E"
for errors, "W" for warnings and "N" for notices.
If no error has been detected, both functions will return NULL.
Example :
$bc-> paint( $data );
$status = $bc->getErrorCode();
if ( $status === NULL OR $status[0] == 'N' )
ok_process();
else
if ( $status == 'W_TRUNCATED' )
ask_user_to_reduce_data_size();
else
other_error_found();
show the errors to the user
setErrorShowMode( string types, string mode [, string predefined_text [,
string image_file ] ] )
sets how errors will (or won't) be shown to the user.
Parameters :
- types: Defines which types of errors will be affected by the setting. Must
be a string containing 1 to 3 characters, of the following allowed : EWN.
- mode: Defines which show mode to use. Three allowed values : "IMG","TXT"
and "NO".
- predefined_text: for IMG and TXT modes, sets a fixed text that will be used
instead of the error description. Can be omitted or set to NULL so in both
cases the specific error description will be used.
- image_file: for the IMG mode, it should be the relative path to an image
file
There are three modes for showing errors :
- 'IMG' (image): default and recommended mode: shows the error inside the
resulting image.
- 'TXT' (text): shows the error as plain text. Note that, unless you output
the image to a file, the image won't show as it will be replaced by the error
text. In such case note that, if you are calling the script from an img tag
you will get a broken image or some error message from the browser.
- 'NO': error showing disabled. This may be fine for notices and warnings
but note that for errors you should process the error from your script, because
otherwise your browser will show a broken image or generic error.
Defaults are : show image for errors and warnings and ignore notices. This
is equivalent to :
$bc->setErrorShowMode( 'EW', 'IMG' );
$bc->setErrorShowMode( 'N', 'NO' );
Examples :
show all error types as text :
$bc->setErrorShowMode( 'EWN', 'TXT' );
disable showing warnings :
$bc->setErrorShowMode( 'W', 'NO' );
show a generic message using an ad hoc image :
$bc->setErrorShowMode( 'EW', 'IMG, 'SOME ERROR WAS FOUND', 'imgs/error.png' );
error logging
setErrorLogMode( string types, string mode [, string $file ] )
Parameters :
- types: Defines which types of errors will be affected by the setting. Must
be a string containing 1 to 3 characters, of the following allowed : EWN.
- mode: Defines which log mode to use. Three allowed values : "PHP","FILE"
and "NO".
- file : log file for mode 'FILE'
Explanation of modes :
- 'PHP': uses PHP error logging (calls trigger_error() ). This is the default
for all error types.
- Errors are logged as E_USER_WARNING, while warnings and notices are
logged as E_USER_NOTICE. This is done this way in order to avoid E_USER_ERROR
as it would abort the script execution.
- Note that if you have PHP error logging off, no logging will be done.
- If you have display_errors on, it will be disabled to avoid broken images.
Use the error showing options if you want to see the error messages in
the browser.
- 'FILE': logs errors to a file, which path is provided as a second parameter.
- 'NO': disables logging.
Example: log all errors to a file :
$bc->setLOgMode( 'EWN', 'FILE', 'logs/RMaxiCode_errors.txt' );
Error codes currently used
E_NO_DATA |
No data to encode was supplied |
E_INVALID_DATA |
Incorrect value for Postal Code, Country code or Service Class. |
E_INTERNAL |
Internal error --it shouldn't happen |
W_TRUNCATED
|
Data provided does not fit in the maximum number of symbols, with the
mode used, so it has been truncated. |
N_MODE_CHANGED |
Alphanumeric postal code was supplied for mode 2, so the mode has been
changed to mode 3. |
|