Click here to Skip to main content
13,007,176 members (55,058 online)
Click here to Skip to main content
Add your own
alternative version


178 bookmarked
Posted 10 Jun 2006

GenCode128 - A Code128 Barcode Generator

, 10 Jun 2006
Rate this:
Please Sign up or sign in to vote.
Create Code128 barcodes for WinForms or ASP.NET.

Sample Image - GenCode128.png


This is a simple library that lets you do one thing very easily: generate an Image for a Code128 barcode, with a single line of code. This image is suitable for print or display in a WinForms application, or even in ASP.NET.


Support for other barcode symbologies can be easily found because they're easy to create. Basic Code39 barcodes, for example, can be produced using nothing but a simple font, and it seems like you can't hardly swing a cat without hitting a Code39 font or imageset for download.

However, Code39 has deficiencies. The naive font-derived output doesn't afford any error checking. In their standard configuration, most scanners can only recognize 43 different symbols (configuration changes may fix this, but you may not have that luxury with your users' choice of hardware configuration). And Code39 is fairly verbose, requiring a large amount of space for a given message.

Code128, on the other hand, has out-of-the-box support for all 128 low-order ASCII characters. It has built-in error detection at the character and message level, and is extremely terse. Unfortunately, producing a reasonable encoding in this symbology is an "active" process. You must analyze the message for the optimal encoding strategy, and you must calculate a checksum for the entire message.

In my case, it was an absolute necessity to encode control characters. My application's design demanded that the user be able to trigger certain menu shortcut keys by scanning a barcode on a page. But since I've got no control over the scanners that my users are employing, the Code39EXT symbology wasn't a good candidate.

A search yielded several Code128 controls, but these had two important deficiencies. First, they were controls. That would be fine if I just wanted to produce a barcode on the page, but I wanted to use them as images in a grid, so I needed a means of obtaining a raw GDI+ Image object. Second, they were fairly expensive -- enough that a license covering all of our developers would cost more than my time to roll my own.

Using the code

Basic usage

As promised, producing the barcode Image is as simple as a single line of code. Of course, you'll still need code lines necessary to put that Image where it needs to go.

Here's a chunk from the sample application. In it, I respond to a button click by generating a barcode based on some input text, and putting the result into a PictureBox control:

private void cmdMakeBarcode_Click(object sender, System.EventArgs e)
      Image myimg = Code128Rendering.MakeBarcodeImage(txtInput.Text, 
                                         int.Parse(txtWeight.Text), true);
      pictBarcode.Image = myimg;
   catch (Exception ex)
      MessageBox.Show(this, ex.Message, this.Text);

Obviously, the meat of this is the first line following the try. For the caller, there's just one interesting method in the whole library:

GenCode128.Code128Rendering.MakeBarcodeImage( string InputData, 
                              int BarWeight, bool AddQuietZone )

(That's the GenCode128 namespace, in a static class called Code128Rendering). Since this is a static class, you don't even need to worry about instantiating an object.

There are three parameters:

  • string InputData

    The message to be encoded

  • int BarWeight

    The baseline width of the bars in the output. Usually, 1 or 2 is good.

  • bool AddQuietZone

    If false, omits the required white space at the start and end of the barcode. If your layout doesn't already provide good margins around the Image, you should use true.

You can get a feel for the effect of these values by playing with the sample application. While you're at it, try printing out some samples to verify that your scanners can read the barcodes you're planning to produce.


A barcode library is pretty much useless if you don't use it to print. You can't very well scan the screen. It's been quite a long time since I had printed anything from a Windows application, and it took a little while to remember how. If you need a quick reminder like I did, take a look at the event that the demo app's Print button calls.

What you should be aware of

First of all, I don't have any exception handling built into the library itself. For your own safety, you should put try/catch blocks around any calls to the library.

The solution comprises three projects. One is the library itself, one is the demo application, and then there is the unit test code. I used NUnit by way of If you don't have that, then Visual Studio is going to complain. Since it's just test code, you can safely drop it and still use the library successfully.

Another point is the required vertical height of the barcode. The spec requires that the image be either 1/4" or 15% of the overall width, whichever is larger. Since I don't have any control of the scaling you're using when outputting the image, I didn't bother implementing the 1/4" minimum. This means that for very short barcode, the height might be illegally small.

Code128's high information density derives partly from intelligently shifting between several alternate codesets. Obtaining the optimal encoding is, as far as I can tell, a "hard" problem (in the sense of discrete math's non-polynomial problems like the Traveling Salesman). The difference between the best possible solution and my pretty good one should be small, and doesn't seem worth the effort.

My algorithm for obtaining a "pretty good" encoding involves a single-character look-ahead.

  • If the current character can be encoded in the current codeset, then it just goes ahead and does so.
  • Otherwise, if the next character would be legal in this codeset, it temporarily shifts into the alternate codeset for just this character.
  • Else, both this character and the next would need a shift, so instead it changes codesets to avoid the shifts.

A similar decision has to be made about which codeset to start the encoding in. To solve this, I check the first two characters of the string, letting them "vote" to see which codeset they prefer. If there's a preference for one codeset, I choose it; otherwise, I default to codeset B. This is because codeset A allows uppercase alpha-numerics plus control characters, while codeset B allows upper and lower alpha-numerics; I assume that you're more likely to want lowercase than control characters.

Finally, there is an optimization in the Code128 spec for numeric-only output that I didn't take advantage of. Long runs of digits can be encoded in a double density codeset. Accounting for this in my already-ugly look-ahead algorithm would have taken a lot more effort -- for a feature that I don't need. But if you have lots of digits and space is tight, you might look at enhancing this.

Points of interest

I suppose that anyone examining my source code will wonder why in the world my table of bar width has two extra columns. In any sane universe, there should be six columns rather than eight. This was a compromise to allow for the oddball STOP code, which has seven bars rather than six. I could have implemented a special case for just this code, but that was too distasteful.

Instead, I added extra zero-width columns to everything else, making the data equivalent in all cases. For every bar that comes up with a zero width, nothing is output, so nothing is harmed.

Of course, the choice between six or eight columns just begs the question: why not seven? This is to accommodate an optimization in the rendering code. By pre-initializing the entire image to white, I can avoid needing to draw the white bars. Thus, I grab bar widths in groups of two. The first one is the black one, and I draw that normally (unless its width is zero). The second one is white, but there's white already there, so I can just skip the area that would have occupied.

If anyone's keeping score, this is my second attempt at truly Test-Driven Development. On the whole, I think this worked out pretty well. Especially, at the lower levels of code, I'm pretty confident of the code. However, the highest level -- where the output is just an Image -- seemed impractical to be tested in this way.

One problem I've got with the TDD, though, is code visibility. Optimally, this library should have exactly one publicly-visible class, with one public method. However, my test code forces me to expose all of the lower-level stuff that the end caller should never know about. If TDD in C# has developed a good answer to that, I haven't yet stumbled upon it.


  • - 2006-06-10

    Initial release.


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


About the Author

Chris Wuestefeld
Web Developer
United States United States
Chris has been developing software since the 80s, and is currently a project manager at SHI in New Jersey where he builds ecommerce applications. Technologically he concentrates primarily on OO and relational databases, and is currently working in .Net technologies. He's also co-author of "Inside ISAPI".

He thinks that programming is easy, the really challenging work is figuring out what an application needs to do in the first place.

You may also be interested in...

Comments and Discussions

GeneralRe: please help me! Pin
ChowMatch19-May-13 19:34
memberChowMatch19-May-13 19:34 
GeneralRe: please help me! Pin
jokefan16-Sep-13 16:42
memberjokefan16-Sep-13 16:42 
Questionthank you and ask about new issue Pin
dev_moh8-Apr-13 20:16
memberdev_moh8-Apr-13 20:16 
AnswerRe: thank you and ask about new issue Pin
Chris Wuestefeld9-Apr-13 0:36
memberChris Wuestefeld9-Apr-13 0:36 
GeneralMy vote of 5 Pin
JohnHSpen26-Mar-13 4:16
memberJohnHSpen26-Mar-13 4:16 
Questionfree code 128 generator Pin
Barcoding House24-Jan-13 15:13
memberBarcoding House24-Jan-13 15:13 
Generalfont yardımı ile barkod oluşturmak Pin
digitaldunyam17-Jan-13 21:39
memberdigitaldunyam17-Jan-13 21:39 
QuestionBarcode Generator Pin
harrisgrah14-Jan-13 22:24
memberharrisgrah14-Jan-13 22:24 
AnswerRe: Barcode Generator Pin
Chris Wuestefeld15-Jan-13 1:09
memberChris Wuestefeld15-Jan-13 1:09 
QuestionCreate Barcode&QRcode Pin
Member 917112825-Nov-12 21:20
memberMember 917112825-Nov-12 21:20 
GeneralASPX helper page for use in ASPX pages. Pin
Member 960051014-Nov-12 18:34
memberMember 960051014-Nov-12 18:34 
QuestionBarcode width gets smaller (relative to height) the longer the barcode Pin
Adam Cooke14-Oct-12 22:58
memberAdam Cooke14-Oct-12 22:58 
AnswerRe: Barcode width gets smaller (relative to height) the longer the barcode Pin
Chris Wuestefeld15-Oct-12 4:16
memberChris Wuestefeld15-Oct-12 4:16 
GeneralRe: Barcode width gets smaller (relative to height) the longer the barcode Pin
Adam Cooke15-Oct-12 4:21
memberAdam Cooke15-Oct-12 4:21 
If you generate the barcoed "1234" you can calculate the width/hight ratio if you then do the same for say "12345" the height in px changes and you also you get a lower ratio width/height when it should be higher as the barcode is longer.

I'm guessing it is something to do with Line 151 in Code128Rendering.cs:
height = Convert.ToInt32( System.Math.Ceiling( Convert.ToSingle(width) * .15F) );

In the end I decided to pass the barcode height as a parameter.
QuestionUnit testing approach WRT everything is public Pin
alanevans26-Sep-12 1:03
memberalanevans26-Sep-12 1:03 
QuestionUnable to generate barcode of 1 and 2 digit length strings Pin
azeem_nawaz7-Sep-12 20:10
memberazeem_nawaz7-Sep-12 20:10 
AnswerRe: Unable to generate barcode of 1 and 2 digit length strings Pin
alanevans26-Sep-12 0:54
memberalanevans26-Sep-12 0:54 
GeneralRe: Unable to generate barcode of 1 and 2 digit length strings Pin
Chris Wuestefeld26-Sep-12 2:10
memberChris Wuestefeld26-Sep-12 2:10 
QuestionHow to read text from a barcode image Pin
san.123431-Aug-12 11:10
membersan.123431-Aug-12 11:10 
AnswerRe: How to read text from a barcode image Pin
alanevans26-Sep-12 0:59
memberalanevans26-Sep-12 0:59 
QuestionGreat!!!! Awesome~!!! You ROCK!!!!! Pin
davidshin24-Aug-12 11:54
memberdavidshin24-Aug-12 11:54 
GeneralMy vote of 5 Pin
Marcus Kramer22-May-12 9:40
memberMarcus Kramer22-May-12 9:40 
Question.NET report rdlc barcode Pin
Member 243361629-Mar-12 16:21
memberMember 243361629-Mar-12 16:21 
QuestionMy Vote of 5 Pin
Maximus Byamukama27-Mar-12 1:40
memberMaximus Byamukama27-Mar-12 1:40 
GeneralMy vote of 5 Pin
manoj kumar choubey26-Feb-12 19:59
membermanoj kumar choubey26-Feb-12 19:59 
Questioncode128 Pin
montas1-Feb-12 22:39
membermontas1-Feb-12 22:39 
Questioncode 128 generator for .net Pin
KeepDynamic15-Jan-12 4:48
memberKeepDynamic15-Jan-12 4:48 
Questionnunit.framework reference Pin
tanajo25-Oct-11 11:59
membertanajo25-Oct-11 11:59 
AnswerRe: nunit.framework reference Pin
Chris Wuestefeld25-Oct-11 16:19
memberChris Wuestefeld25-Oct-11 16:19 
QuestionI need to use 11 charecter but the width will be more reduced than the size is coming now for weight 1 Pin
Mahbub42221-Oct-11 8:06
memberMahbub42221-Oct-11 8:06 
Questionbarcodes are WAY too long? Pin
Member 819802729-Aug-11 13:10
memberMember 819802729-Aug-11 13:10 
GeneralMy vote of 5 Pin
Blake7715-Jul-11 7:40
memberBlake7715-Jul-11 7:40 
GeneralRe: My vote of 5 Pin
Member 70962713-Nov-11 9:40
memberMember 70962713-Nov-11 9:40 
GeneralMy vote of 5 Pin
Mydhili Govindarajula27-Jun-11 4:22
memberMydhili Govindarajula27-Jun-11 4:22 
GeneralAnother method to try with TTF font and .NET dll Pin
paperwater15-Apr-11 8:39
memberpaperwater15-Apr-11 8:39 
GeneralTwo extra row space of labels are coming after printing Pin
pre1e1jo14-Apr-11 2:01
memberpre1e1jo14-Apr-11 2:01 
GeneralUsing in a webpage Pin
John Woodraska1-Feb-11 6:43
memberJohn Woodraska1-Feb-11 6:43 
GeneralUsage of ASCII representing FNC3 and CR Pin
GZ123430-Nov-10 4:09
memberGZ123430-Nov-10 4:09 
GeneralNeed to get the width smaller for a label I am using Pin
Reggie Rippetoe22-Sep-10 10:23
memberReggie Rippetoe22-Sep-10 10:23 
GeneralRe: Need to get the width smaller for a label I am using Pin
DuffMeisterMoo25-May-13 20:37
memberDuffMeisterMoo25-May-13 20:37 
GeneralReport with barcode Pin
descention31-Aug-10 3:21
memberdescention31-Aug-10 3:21 
QuestionCreating intermediate string Pin
Jeanne Brazel24-Aug-10 3:39
memberJeanne Brazel24-Aug-10 3:39 
AnswerRe: Creating intermediate string Pin
Chris Wuestefeld24-Aug-10 4:02
memberChris Wuestefeld24-Aug-10 4:02 
GeneralRe: Creating intermediate string Pin
envprogrammer24-Aug-10 4:07
memberenvprogrammer24-Aug-10 4:07 
AnswerRe: Creating intermediate string Pin
johannesnestler24-Aug-10 4:10
memberjohannesnestler24-Aug-10 4:10 
GeneralRe: Creating intermediate string Pin
envprogrammer24-Aug-10 4:50
memberenvprogrammer24-Aug-10 4:50 
GeneralReporting Services Barcode Print Pin
John Woodraska14-Jul-10 3:46
memberJohn Woodraska14-Jul-10 3:46 
GeneralRe: Reporting Services Barcode Print Pin
Chris Wuestefeld14-Jul-10 5:20
memberChris Wuestefeld14-Jul-10 5:20 
GeneralRe: Reporting Services Barcode Print Pin
sanoobka9-Aug-10 21:13
membersanoobka9-Aug-10 21:13 
GeneralRe: Reporting Services Barcode Print Pin
Thomas Fraefel28-Aug-10 3:31
memberThomas Fraefel28-Aug-10 3:31 

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 | Terms of Use | Mobile
Web02 | 2.8.170628.1 | Last Updated 10 Jun 2006
Article Copyright 2006 by Chris Wuestefeld
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid