Click here to Skip to main content
14,037,160 members
Click here to Skip to main content
Add your own
alternative version


1.5K bookmarked
Posted 10 Oct 2007
Licenced Apache

Barcode Image Generation Library

, 12 Nov 2014
Rate this:
Please Sign up or sign in to vote.
This library was designed to provide a class for developers to use, that allows generation of barcode images from a string of data.



This article and its code provide a way for developers to put barcodes into their applications. It allows for the generation of barcode images without the use of "barcode fonts". This need arose out of the necessity in one of my own projects to use barcodes and the lack of free libraries on the web.

To give an idea of what happens in this library: it first turns the data into a series of 1s and 0s representing equal-width bars and spaces. This string of binary information is then sent to a drawing method that converts it to an image representing the desired barcode. This approach allows for one common drawing method to be used on all symbologies.

Supported Encoding Types

Code 128 Code11 Code 39 (Extended / Full ASCII)
Code 93 EAN-8 EAN-13
MSI ISBN Standard 2 of 5
Interleaved 2 of 5 PostNet UPC Supplemental 2
UPC Supplemental 5 Codabar ITF-14
Telepen Pharmacode FIM (Facing Identification Mark)

** Keep in mind that some symbologies go by more than one name, so make sure the one you are using isn't listed above by a different name before contacting me to add it. If it isn't listed above and you would like me to look at adding it to this library, please post a comment below, and I will take a look at it as soon as possible. (Bugs are always a priority, so please send me bug reports.)

Using the Code

The library contains a class called BarcodeLib. There are three constructors:

Barcode (string, BarcodeLib.TYPE);

If you decide to create an instance with parameters, the parameters are as follows: the string is the data to be encoded into the barcode, and BarcodeLib.TYPE is the symbology to encode the data with. If you do not choose to specify the data and type at the time the instance is created, you may specify them through the appropriate property later on (but before you encode).

BarCodeLib.Barcode b = new BarCodeLib.Barcode(BarCodeLib.TYPE.UPCA, 
          "038000356216", Color.Black, Color.White, 300, 150);

To get the image representing the data generated, you must then call one of the many Encode functions.

public Image Encode(TYPE iType, string StringToEncode, int Width, int Height)
public Image Encode(TYPE iType, string StringToEncode, 
        Color ForeColor, Color BackColor, int Width, int Height)
public Image Encode(TYPE iType, string StringToEncode, Color ForeColor, Color BackColor)
public Image Encode(TYPE iType, string StringToEncode)
Encode(TYPE iType)

The resulting Image contains the barcode in image format. More functionality has been added, so you can save the Image once it is encoded.

public void SaveImage(string Filename, SaveTypes FileType)

This function can be used by specifying the full path (filename included) of the location you would like to save the image to as a string. The second parameter is an enumerator (BarcodeLib.SaveTypes) that represents the supported types (JPG, BMP, PNG, GIF, TIFF) of files you can save. Functionality has been added so that you can now set the IncludeLabel parameter to allow it to draw the data that's encoded in the barcode, below the image, as a label. Keep in mind that this will take up some of the space you specify for the size of the image.

b.IncludeLabel = true;

This is used to put the data encoded at the bottom of the image. If you do not set this parameter, it will just generate the barcode without the data at the bottom.

Points of Interest

Writing this library offered me the chance to become intimately familiar with how barcode symbologies work and how the symbologies differ from one another.

A new property has been added to allow exportation of the image and properties in XML format. Keep in mind that the barcode must be encoded first before this property is read; otherwise, an error will be thrown to notify you of this mistake.



  • October 10, 2007
    • Initial release (bugs most certainly exist, and a couple of symbologies need to be modified/implemented).
  • October 16, 2007
    using (Graphics g = Graphics.FromImage(b))
        g.DrawLine(new Pen(c), x, 0, x, b.Height);
        g.DrawLine(new Pen(c), x + 1, 0, x + 1, b.Height);
    • Updated Encode_Code39() to fix a bug that didn't include inter-character spaces.
    • Also, updated the function Generate_Image(Color, Color), and replaced the section using SetPixel with the following:
  • October 17, 2007
    using (Graphics g = Graphics.FromImage(b))
        g.DrawLine(new Pen(c, (float)2), new Point(x, 0),
        new Point(x, b.Height));
    • Changed the Generate_Image(Color, Color) function again to be a little more efficient. Instead of drawing two lines, it just uses a 2px-wide pen now.
    • Added the ability to call BarcodeLib.Generate_Labels(Image), it will add the label showing the data encoded at the bottom of the barcode.
    • Fixed a bug in the Test application where, if you encoded with PostNet as the type, it would automatically try to put the label at the bottom and labels aren't available on PostNet images. This caused it to throw an error that a try{}catch{} can handle for now.


    • Took c0ax_lx's advice and moved...

      using (Graphics g = Graphics.FromImage(b))

      ... outside the while loop to improve resource usage.

  • October 26, 2007
    • Article edited and moved to the main CodeProject article base.
  • November 1, 2007
    • Complete restructuring of the library to abstract portions of it. Should be much cleaner to look at.
    • An interface was added to force any updates to adhere to the structure.
    • There were some bugs that were fixed in this release.
    • Some of the encoding types on the menu were encoding with a different type than they said.
    • Changed CheckNumericOnly() to be one line of code instead of a massive O^2 complicated take. (Thanks, Pete!)
  • December 9, 2007
    int pos = 0;
    • Bug fixed in UPC-E encoding that would cause an index-out-of-range exception to be thrown. (Thanks Luca Z.)
    • This library is getting better with the help of people like Luca and Pete. Keep up the good work, friends.
  • April 16, 2008
    • Code 128 support (beta) (the FNC* chars are still not encoding right... I have to figure that out), but ... it's at least here for your trial and for your comments.
    • Also, there were a few country codes left out of the EAN-13 assigning country lookup. I added what I could find that I left out.
    • Changed the CheckNumericOnly() back to a more complex task because some data being encoded was longer than what Int64.TryParse(string, out) could handle ... so back to a more complex, but still a faster, task than comparing each char. Now, I break the string into pieces and test each piece.
  • May 3, 2008
    • Code 128 had some bug fixes added.
    • One was present in InsertStartandCodeCharacters().
    • Bug fixed when trying to encode an apostrophe, it needed an escape character when selecting the data for it from the dataset.
  • May 27, 2008
    • PostNet now supports 5, 6, 9, 11 digit data.
    • Also, a bug with the check-digit for PostNet is fixed.
    • Code 128 now supports specifying and locking the encoding to a specific type (Code A, B, C).
    • Code 39 Extended (Full ASCII) is now supported.
  • May 29, 2008
    • Bug fixed (thanks in Bitmap Generate_Image(Color DrawColor, Color BackColor) that caused the drawing to be off by one horizontal pixel. This caused the drawing to cut 1 pixel width off the first bar that was drawn if it was drawn up against the edge of the image.
    • The drawing function also changed a bit to eliminate the variable int x; from the function.
    • All positions are now calculated off the variable int pos;, which cuts out one unnecessary and confusing variable.
  • July 30, 2008
    this.C128_Code.CaseSensitive = true;
    • Bug fixed (thanks Kazna4ey and WolfgangRoth) in init_Code128() that caused .Select(string filterExpression) to return the wrong rows due to case insensitivity. So, the following was added:
    • Another function byte[] GetImageData(SaveTypes savetype) was added so that users may request the bytes of the image easily. (Useful if using Crystal Reports, etc.)
  • August 26, 2008
    • Bug fixed (thanks JackyWu2005) in Code128.cs that was preventing the proper start characters from being inserted. This only happened when switching back to A from any other encoding type.
  • October 20, 2008
    • Added ITF-14 and Code93.
    • Fixed a bug in Save As functionality that was not saving files in the selected format.
    • Labels now show checksums except in C128 and C11.
  • December 3, 2008
    • Can now specify image size before encoding.
    • Complete overhaul of the drawing function to allow for dynamic drawing size. Now calculates the bar width based on the specified image size. Removed resize functions due to inaccuracy of the resizing method. The encoding functions have been revamped to reflect these changes (removed some of the overloaded functions referencing the resize functions). Also removed a majority of the case statements from Generate_Image() to simplify it. Updated the article to reflect the changes to the Encode functions and the changes to the drawing functions.
  • February 11, 2009
    • Fixed bug in Code 128C that would not insert a 0 in front of an odd length string of raw data.
    • Fixed a bug (thanks Shaihan Murshed) in Code 39 that let the user encode * in the string of data. This should only be used for starting characters, and is now handled.
    • Fixed a bug in Code 39 that was inserting an extra 0 at the end of the encoded string. This did not affect the validity of the barcodes, it was just not supposed to be there.
    • Added a new property to the library called FormattedData. This value is what is actually encoded. It is formatted for certain types of barcodes, for example, Code 39 requires * in front and behind the barcode.
  • June 4, 2009 (
    • Fixed a bug in Code128-A and Code128-B that would cause it to encode incorrectly due to incorrectly trying to compact the barcode for Code128-C. This functionality is now bypassed if Code128-A or Code128-B is selected.
    • Removed a useless variable bEncoded from BarcodeLib.cs.
    • static methods now support generating the data label (required addition of a parameter to 3 of the 5 static methods used to encode).
    • Property now available to retrieve the amount of time (EncodingTime) it took to encode and generate the image. (Might be helpful for diagnostics.)
    • Modified a few error messages to be more descriptive about correcting the problem with data length.
    • The Barcode class now inherits from IDisposable - XML export functionality added to BarcodeLib to allow the data, encoded data, and other properties to be exported in XML along with the image in Base64String format. This includes functionality to GetXML() and GetImageFromXML(BarcodeXML).
    • To go along with the XML functionality, there is now a dataset included that has the basic layout of the XML data to make importing and exporting easy.
    • ImageFormat is now a property to set to select what type of image you want returned (JPEG is default). This can help speed of transferring data if using a Web Service.
    • ITF-14 now draws the label with the proper background color instead of always being white.
  • August 16, 2009 (
    • Fixed a bug that allowed non-numeric data to be encoded with Code128-C, a check has been put in place to handle this. It throws an error EC128-6 now, if found to contain something that isn't in Code128-C.
    • Fixed a bug in GetEncoding() for C128. This would allow Code128-B to switch and dynamically use Code128-A if it couldn't find a char in its set.
  • November 2, 2009 (
    • Changed the use of a Pen object that was not disposed of. This was not causing a problem, just bad technique.
    • Fixed an encoding issue with C128-B that had a wrong character in its encoding set at one point (U instead of Z in codeset B).
  • January 4, 2010 (
    • The UPC-A check digit is now calculated every time whether 11 or 12 digits are passed in. If 12 is passed in and it has got an incorrect check digit, then it is replaced with the correct check digit. This prevents an unscannable barcode from being generated.
    • The EAN13 check digit is now calculated every time whether 12 or 13 digits are passed in. If 13 is passed in and it has got an incorrect check digit, then it is replaced with the correct check digit. This prevents an unscannable barcode from being generated.
    • All errors can be accessed via the BarcodeLib.Errors properties which is a list of separate errors encountered.
    • All symbologies were moved to the BarcodeLib.Symbologies namespace for better organization.
    • The FormattedData property was not being used, so it was removed.
    • The Version property was added to BarcodeLib to allow reading the libraries version number.
  • April 28, 2010 (
    • Fixed a bug in Code 39 extended that was erasing the start and stop characters if extended was used.
    • Fixed a bug that if barcodes were aligned left or right, they would cut off a part of the starting or ending bar, which was a drawing bug that's been present since
    • Fixed a bug in Code 128C that checked for numeric data; if it was bigger than Int64 and was numeric, it would throw an exception saying it was non-numeric data.
    • Fixed a bug in UPC-A that encoded with the same sets as EAN-13 and only CodeA and CodeC should have been used.
    • Made the Version property static so it can be read without creating an instance.
    • Added a LabelFont property to allow the labels font to be changed.
    • Restructured the label drawing functions to take font height and use that to determine the height of the label.
    • Created an IsNumeric function in C128-C to better separate that functionality. Replaced Int64 with Int32 to better allow compatibility with x86 processors.
    • EncodingTime now includes the time to draw the image and not just the encoding.
    • Alignment property added to allow aligning the barcode in the image given if the image space is wider than the drawn barcode. (Default is centered.)
    • Postnet drawing is incorporated into the default drawing case now, which shortens the code and gets rid of some redundant code.
    • Telepen symbology added.
  • July 18, 2010 (
    • Fixed a bug in Code 93 that caused four characters to be encoded incorrectly.
    • Fixed a bug where the ITF-14 bearer bars were not drawing evenly.
    • Fixed a bug in Codabar that would report an object not set to a reference error if non-numeric is found.
    • Added property LabelPosition to position label above or below the barcode, and align the label left, right, or center.
    • Added property RotateFlipType to allow rotation/flipping the image before it is returned.
    • Added several of the newer properties to the XML output of GetXML().
    • Removed Codabar start / stop characters in the label.
    • IsNumeric function added to BarcodeCommon so that every symbology has access to it.
  • June 16, 2011 (
    • Fixed a bug in drawing of barcodes that caused barcodes to be cut off on the left and right when aligned to the sides.
    • Fixed a bug in the project where the BarcodeXML dataset was corrupt.
    • Added the GetSizeOfImage function that returns the real world coordinates of the EncodedImage.
    • Facing Identification Mark(FIM) symbology added. 
  • June 12, 2012 (
    • Corrected comments on class summaries
    • Eliminated some unnecessary private variables  
  • June 12, 2012 ( 
    • Added a byte array representation of the encoded image (Encoded_Image_Bytes) which can be used in Crystal Reports. See (Barcodes in Crystal Reports
    • Updated the XML schema to use integers instead of Enums due to versioning conflicts.  
  • June 16, 2013 (  
    • Fixed a bug in the Codabar symbology that would not allow valid non-numeric characters from being encoded.
    • Fixed a bug that would not encode C128-C codes with FNC1 in the starting characters.
    • Fixed a bug in the ITF-14 check digit calculation where it would calculate the wrong check digit most of the time.  
  • November 23, 2013 (
    • Removed duplicate IsNumeric check method, moved CheckNumericOnly method to BarcodeCommon
    • Pharmacode symbology added.
  • September 27, 2014 (
    • Fixed a bug in Code 11 where K checksums were being calculated for messages shorter than 10 characters in length.
    • Fixed a bug in PostNet that drew incorrectly for all PostNet barcodes (thanks jonney3099)
    • Added Code 39 Mod 43 support
    • Updated the GetImageSize method to return an ImageSize object containing the real world size of the image generated.
  • October 26, 2014 (
    • cleaned up layout of test application
    • added alternate label text property
  • October 30, 2014 (
    • Fixed bug in Code 39 Mod 43 check digit calculation
  • July 29, 2016 (
    • Fixed bug in UPC-E encoding


This article, along with any associated source code and files, is licensed under The Apache License, Version 2.0


About the Author

Brad Barnhill
Software Developer Cerner Corporation
United States United States
Brad Barnhill has a Masters in Nursing from the University of Tennessee (UTHSC), and a Bachelors in Computer Science from UT as well. His interests are C#, barcodes, developing controls for other developers to use, and distributed computing. Android development is also an interest and contributing to open source projects. He has been employed as a software engineer since 2004.

You may also be interested in...


Comments and Discussions

QuestionProblem in Reports(RDLC) Pin
s.mozaffari22-Oct-07 12:04
members.mozaffari22-Oct-07 12:04 
AnswerRe: Problem in Reports(RDLC) Pin
Brad Barnhill23-Oct-07 15:43
memberBrad Barnhill23-Oct-07 15:43 
GeneralRe: Problem in Reports(RDLC) Pin
s.mozaffari24-Oct-07 12:43
members.mozaffari24-Oct-07 12:43 
GeneralRe: Problem in Reports(RDLC) Pin
Brad Barnhill24-Oct-07 14:53
memberBrad Barnhill24-Oct-07 14:53 
GeneralRe: Problem in Reports(RDLC) Pin
s.mozaffari25-Oct-07 5:39
members.mozaffari25-Oct-07 5:39 
GeneralRe: Problem in Reports(RDLC) Pin
s.mozaffari25-Oct-07 6:17
members.mozaffari25-Oct-07 6:17 
GeneralRe: Problem in Reports(RDLC) Pin
s.mozaffari25-Oct-07 7:25
members.mozaffari25-Oct-07 7:25 
AnswerRe: Problem in Reports(RDLC) Pin
giague4-Jul-12 7:43
membergiague4-Jul-12 7:43 
I did it!!!!

Just create a public property:
public byte[] Encoded_Image_Stream
                MemoryStream ms = new MemoryStream();
                _Encoded_Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                return ms.ToArray();


Then cann pass the Barcode class as Report DataSource

BarCodeLib.Barcode b = new BarCodeLib.Barcode(BarCodeLib.TYPE.UPCA, 
          "038000356216", Color.Black, Color.White, 300, 150);

List<BarcodeLib.Barcode> lBC = new List<BarcodeLib.Barcode>();
reportViewer1.LocalReport.DataSources.Add(new Microsoft.Reporting.WinForms.ReportDataSource("BarcodeLib_Barcode", lBC));

and put a Picturebox in your RDLC file with these settings:

MimeType: image/png
Source: Database
Value: =Fields!Encoded_Image_Stream.Value

You got the barcode in the RDLC picture box.

Hope this help.
GeneralRe: Problem in Reports(RDLC) Pin
Brad Barnhill5-Jul-12 18:10
memberBrad Barnhill5-Jul-12 18:10 
GeneralHTTP Status 404 Pin
Manickarj19-Oct-07 23:24
memberManickarj19-Oct-07 23:24 
GeneralRe: HTTP Status 404 [modified] Pin
Brad Barnhill21-Oct-07 4:02
memberBrad Barnhill21-Oct-07 4:02 
GeneralExcellent piece of work Pin
shmulyeng17-Oct-07 5:25
membershmulyeng17-Oct-07 5:25 
GeneralRe: Excellent piece of work [modified] Pin
Brad Barnhill17-Oct-07 5:33
memberBrad Barnhill17-Oct-07 5:33 
GeneralRe: Excellent piece of work Pin
thbernt20-May-08 1:00
memberthbernt20-May-08 1:00 
GeneralExcelent Pin
metcarob16-Oct-07 6:20
membermetcarob16-Oct-07 6:20 
GeneralRe: Excelent Pin
Brad Barnhill16-Oct-07 8:44
memberBrad Barnhill16-Oct-07 8:44 
GeneralCode 39 problem (and solution) Pin
smallboy8416-Oct-07 3:21
membersmallboy8416-Oct-07 3:21 
GeneralRe: Code 39 problem (and solution) Pin
Brad Barnhill16-Oct-07 4:00
memberBrad Barnhill16-Oct-07 4:00 
GeneralRe: Code 39 problem (and solution) Pin
smallboy8416-Oct-07 20:08
membersmallboy8416-Oct-07 20:08 
GeneralGreat article, and a speed improvement Pin
c0ax_lx16-Oct-07 2:59
memberc0ax_lx16-Oct-07 2:59 
GeneralRe: Great article, and a speed improvement [modified] Pin
Brad Barnhill16-Oct-07 4:06
memberBrad Barnhill16-Oct-07 4:06 
GeneralRe: Great article, and a speed improvement Pin
c0ax_lx16-Oct-07 22:23
memberc0ax_lx16-Oct-07 22:23 
GeneralRe: Great article, and a speed improvement Pin
Brad Barnhill17-Oct-07 9:47
memberBrad Barnhill17-Oct-07 9:47 
GeneralRe: Great article, and a speed improvement Pin
Victor Boba16-Oct-07 6:32
memberVictor Boba16-Oct-07 6:32 
GeneralVery nice Pin
Patrick Etc.10-Oct-07 9:29
memberPatrick Etc.10-Oct-07 9:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web03 | 2.8.190424.1 | Last Updated 12 Nov 2014
Article Copyright 2007 by Brad Barnhill
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid