5,447,640 members and growing! (21,423 online)
Email Password   helpLost your password?
General Programming » Macros and Add-ins » Add-ins/Plug-ins     Intermediate License: The Code Project Open License (CPOL)

Barcode Image Generation Library

By Brad Barnhill

This library was designed to give an easy class for developers to use when they need to generate barcode images from a string of data
C# (C# 2.0, C#), Windows (Windows, Win2K, WinXP, Win2003), .NET (.NET, .NET 2.0), Visual Studio (VS2005, Visual Studio), Dev

Posted: 10 Oct 2007
Updated: 28 Aug 2008
Views: 74,905
Bookmarked: 302 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
112 votes for this Article.
Popularity: 9.64 Rating: 4.70 out of 5
3 votes, 2.7%
1
0 votes, 0.0%
2
2 votes, 1.8%
3
10 votes, 8.9%
4
97 votes, 86.6%
5
screenshot.jpg

Introduction

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 for one of my own projects to use barcodes and the lack of free libraries on the Web to do the job.

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 function 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

Codabar Code11 Code 39(Extended / Full ASCII)
Code 128 EAN-8 EAN-13
Interleaved 2 of 5 ISBN JAN-13
MSI PostNet Standard 2 of 5
UPC-A UPC-E UPC Supplemental 2
UPC Supplemental 5

** Keep in mind 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 one class called BarcodeLib. There are three constructors:

Barcode();
Barcode(string);
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 the 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("038000356216",
    BarCodeLib.TYPE.UPCA);

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, double percent)
public Image Encode(TYPE iType, double percent)
public Image Encode(TYPE iType, string StringToEncode, int Width, int Height)
public Image Encode(TYPE iType, int Width, int Height)
public Image Encode(TYPE iType, string StringToEncode, Color DrawColor,
    Color BackColor, double percent)
public Image Encode(TYPE iType, string StringToEncode, Color DrawColor,
    Color BackColor, int Width, int Height)
public Image Encode(TYPE iType, string StringToEncode, Color DrawColor,
    Color BackColor)
public Image Encode(TYPE iType, Color DrawColor, Color BackColor)
public Image Encode(TYPE iType, string StringToEncode)
public Image Encode(TYPE iType)
public Image Encode()

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 call:

public Image Generate_Labels(Image img)

This is used to put the data encoded at the bottom of the image. If you do not call this function, 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.

History

  • October 10th, 2007 - Initial release (bugs most certainly exist and a couple of symbologies need to be modified/implemented)

  • October 16th, 2007 - 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:

    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);
    }//using
  • October 17th, 2007 - 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. Thanks for the comments; they continue to make this library better.

    using (Graphics g = Graphics.FromImage(b))
    {
        g.DrawLine(new Pen(c, (float)2), new Point(x, 0),
        new Point(x, b.Height));
    }//using

    Also, functionality was added so that if you 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 26th, 2007 - Article edited and moved to the main CodeProject article base.

  • November 1st, 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 1 line of code instead of a massive O^2 complicated take. (Thanks, Pete)

  • December 9th, 2007 - Bug fixed in UPC-E encoding that would cause an index out of range exception to be thrown. (Thanks Luca Z.)

    int pos = 0;

    This library is getting better with the help of people like Luca and Pete. Keep up the good work friends.

  • April 16th, 2008 - Code 128 support is here. It is still very much in the beta phase (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. If you find any more, just let me know. Thanks again for your support and help.

    I also had to change 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 3rd, 2008 - Code 128 had some bug fixes added. One was present in InsertStartandCodeCharacters(). The other was when trying to encode an apostrophe, it needed an escape character when selecting the data for it from the dataset. This should fix all the bugs for now ... if you find any more, let me know so I can try to track them down. Thanks again for your support.

  • May 27th, 2008 - PostNet now supports 5, 6, 9, 11 digit data. Also, a bug with the checkdigit 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 29th, 2008 - Bug fixed (thanks Koru.nl) 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 30th, 2008 - 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:

    this.C128_Code.CaseSensitive = true;

    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 26th, 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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Brad Barnhill


Brad Barnhill is currently employed as a software developer in the Memphis area. His interests are C# and the .NET framework. He has been employed as a software developer since 2004. He enjoys sardines and bologna.
Occupation: Software Developer
Location: United States United States

Other popular Macros and Add-ins articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 263 (Total in Forum: 263) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralSave as JPG doesn´t export JPG Format - Bug Reportmembertkreutz22:14 2 Sep '08  
GeneralRe: Save as JPG doesn´t export JPG Format - Bug ReportmemberBrad Barnhill19:40 3 Sep '08  
Generalsome features, BarWeightmemberslava_pvf3:26 29 Aug '08  
GeneralRe: some features, BarWeightmemberBrad Barnhill6:55 31 Aug '08  
GeneralTrying to Use the SaveAdd method from Generate LabelsmemberMember 23428711:28 27 Aug '08  
GeneralRe: Trying to Use the SaveAdd method from Generate LabelsmemberBrad Barnhill10:29 28 Aug '08  
GeneralITF-14memberLCHell0:13 27 Aug '08  
GeneralRe: ITF-14memberBrad Barnhill10:23 28 Aug '08  
GeneralEAN 128 ?memberbobfox12:18 23 Aug '08  
GeneralRe: EAN 128 ?memberBrad Barnhill9:34 25 Aug '08  
GeneralRe: EAN 128 ? [modified]memberLCHell22:02 25 Aug '08  
GeneralRe: EAN 128 ?memberKoru.nl0:52 26 Aug '08  
GeneralRe: EAN 128 ?memberBrad Barnhill7:18 26 Aug '08  
GeneralCode128 issuesmemberKoru.nl2:45 23 Aug '08  
GeneralRe: Code128 issuesmemberBrad Barnhill9:02 25 Aug '08  
GeneralRe: Code128 issuesmemberKoru.nl0:38 26 Aug '08  
QuestionBug ReportmemberJackyWu200523:44 17 Aug '08  
AnswerRe: Bug ReportmemberJackyWu20054:13 18 Aug '08  
GeneralRe: Bug ReportmemberBrad Barnhill13:00 18 Aug '08  
GeneralIMEI Codemembertry.kret22:43 17 Aug '08  
GeneralRe: IMEI CodememberBrad Barnhill12:32 18 Aug '08  
GeneralRe: IMEI Codemembertry.kret16:17 18 Aug '08  
GeneralRe: IMEI CodememberBrad Barnhill10:02 19 Aug '08  
GeneralRe: IMEI CodememberBrad Barnhill10:13 19 Aug '08  
GeneralExcellent work B R A V O !!memberMember 17966146:06 5 Aug '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 28 Aug 2008
Editor: Deeksha Shenoy
Copyright 2007 by Brad Barnhill
Everything else Copyright © CodeProject, 1999-2008
Web11 | Advertise on the Code Project