Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Reading Barcodes from an Image

0.00/5 (No votes)
24 Mar 2004 1  
An example of how to process an image for barcode strings

Introduction

I recently ran across Neil Van Eps series of articles on how to draw barcodes and found myself wondering how easy it would be to process an image to read barcodes. Attached is a demo project that shows one method for reading Code39.

Background

I've been a Basic programmer since age 8 (love those GOTO's... Icky!), a VB4->VB6 programmer for ages (OK... Only since college), and a VB.NET programmer since it was released, but exclusively .NET for only about a year. Basically (sorry for the pun), I've been able to get by with very little knowledge of C or C++. I recently needed to do some image processing so I checked out The Code Project and found a series of articles titled Image Processing for Dummies with C# and GDI+ by Christian Graus. YES! I had finally found what I was looking for, an example on image processing. I started to translate the C# code to VB.NET (usually this is an easy task) and found it nearly impossible... Needless to say, I am now a C# developer as well. :)

Using the code

Although there are at least ten ways (that I can think of) to skin a cat, I selected a method for processing the image that was relatively simple just to prove the concept. First, I create an average of the pixels (histogram) down the image:

 
 
  for(int y=0;y<bmp.Height;++y)
  {
   for(int x=0; x < bmp.Width; ++x )
   {
  // Add up all the pixel values vertically (average the R,G,B channels) 
    vertSum[x] += ((p[0] + (p+1)[0] + (p+2)[0])/3);
    
    p+=3;
   }
   p += nOffset;
  }
 
Next run through the resulting array to find the narrow and wide bars:
 
 
  for(int i = 0; i < vertHist.histogram.Length; ++i)
  {
   ...
  }
 
Finally, lookup the narrow/wide bar pattern to match it to a character:
 
 
  dataString += parsePattern(new string(pattern));
  
 

TODO

The method I used to get the bar pattern isn't what I would call robust. I'd eventually like to figure out a better method for finding the barcode patterns (in any orientation) in addition to adding support for the various barcode types.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here