DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Sheraz has posted 65 posts at DZone. View Full User Profile

Read BarCodes in the Image & Get BarCode Region Information from Image

03.19.2013
| 5583 views |
  • submit to reddit
[C#]
 
// read code39 barcode from image
string image = "code39Extended.jpg";
BarCodeReader reader = new BarCodeReader(image, BarCodeReadType.Code39Standard);
// try to recognize all possible barcodes in the image
while (reader.Read()) {
   // get the region information
    BarCodeRegion region = reader.GetRegion();
    if (region != null)
    {
        // display x and y coordinates of barcode detected
        System.Drawing.Point[] point = region.Points;
        Console.WriteLine("Top left coordinates: X = " + point[0].X + ", Y = " + point[0].Y);
        Console.WriteLine("Bottom left coordinates: X = " + point[1].X + ", Y = " + point[1].Y);
        Console.WriteLine("Bottom right coordinates: X = " + point[2].X + ", Y = " + point[2].Y);
        Console.WriteLine("Top right coordinates: X = " + point[3].X + ", Y = " + point[3].Y);
    }
    Console.WriteLine("Codetext: " + reader.GetCodeText());
}
// close reader
reader.Close();


[VB.NET]

 ' read code39 barcode from image
Dim image As String = "code39Extended.jpg"
Dim reader As New BarCodeReader(image, BarCodeReadType.Code39Standard)
' try to recognize all possible barcodes in the image
While reader.Read()
	' get the region information
	Dim region As BarCodeRegion = reader.GetRegion()
	If region IsNot Nothing Then
		' display x and y coordinates of barcode detected
		Dim point As System.Drawing.Point() = region.Points
		Console.WriteLine("Top left coordinates: X = " & point(0).X & ", Y = " & point(0).Y)
		Console.WriteLine("Bottom left coordinates: X = " & point(1).X & ", Y = " & point(1).Y)
		Console.WriteLine("Bottom right coordinates: X = " & point(2).X & ", Y = " & point(2).Y)
		Console.WriteLine("Top right coordinates: X = " & point(3).X & ", Y = " & point(3).Y)
	End If
	Console.WriteLine("Codetext: " & reader.GetCodeText())
End While
' close reader
reader.Close()
This technical tip shows how to read the image and get all the barcode regions, for all the recognized barcodes in the image. The barcode region is the part of the image that only contains the barcode itself. In a large image, it is possible that there are other texts or images along with the barcode. Getting the barcode region will separate the barcodes from other text/objects in the image by detecting their edges. First, we will read the BarCodes in the image using the BarCodeReader.Read() method. Then, we will get the region of the barcode using BarCodeReader.GetRegion() method, which will return an instance of type BarCodeRegion. We can then get the X and Y coordinates of the barcode using BarCodeRegion.Points property.