C# Barcode Reader: Scan QR Code, Barcode in .NET Applications


How to scan, read linear, 2d barcode images in C# ASP.NET, Windows application?

Reading & Scanning Linear, 2D Barcode Images in Visual C# .NET using C#.NET Barcode Reader



In this C# tutorial, you will learn how to scan an image and read barcode data from it in your C# ASP.NET web app and Windows application.

  • Scan the whole image or partial of the image area
  • Support multiple image formats, such as bitmap, jpg, png, gif, multi-page TIFF
  • Auto detect barcodes with any rotation angles
  • Support QR Code, Data Matrix, Code 128, EAN/UPC, more than 20 2d and 1d barcode formats
  • Scan, extract barcode data with located area information
  • Support .NET 5+, .NET Standard 2.0, .NET Framework 4.x, 3.x, 2.x
  • Step-by-step instruction tutorials for ASP.NET Core, MVC, Web Forms, Windows Forms, WPF projects included

How to scan, read barcodes from image using C#

  1. Download .NET Barcode Reader Library
  2. Install C# library to read barcode from images in .NET apps
  3. Step by Step Tutorial








  • Read and recognize 20+ linear, 2d barcode images in C#
  • Scan and read barcodes from any angle inside the barcode image in any C# development
  • Decode barcodes from Tiff, Bitmap, Gif, Jpeg image types in C#.net class
  • Support quick scan barcodes from specified area inside the image document
  • Completely developed in C#.NET, compatible with .net framework 2.0 and later version
  • Reading and recognizing 2d (matrix) barcode images, including QR Code in C#, PDF-417 in C#, Data Matrix in C#
  • Scanning and recognizing linear (1d) barcode images, including Code 39, Code 128, EAN-13, UPC-A, GS1-128 in C#
  • Mature C#.NET barcode reading component SDK


Install C# Barcode Reader library

Install through NuGet

For .NET Core apps on Windows
PM > Install-Package OnBarcode.Barcode.Reader


For .NET Core apps on non-Windows (Linux, MacOS, ...)
PM > Install-Package OnBarcode.Barcode.Reader.SkiaSharp


For .NET Framework application
PM > Install-Package OnBarcode.Barcode.Reader.Framework




Install through downloaded DLLs

For .NET (5+), and .NET Core on Windows

  • Add .net dll OnBarcode.Barcode.BarcodeScanner.dll from {Download package}/dll/NetStandard2.0/ to your .net project
  • Add NuGet Package System.Drawing.Common from NuGet Package Manager to your .net project


For .NET (5+), and .NET Core on non-Winodws, such as Linux, MacOS

  • Add .net dll OnBarcode.Barcode.BarcodeScanner.Skia.dll from {Download package}/dll/NetStandard2.0/ to your .net project
  • Add NuGet Package SkiaSharp from NuGet Package Manager to your .net project


For .NET Framework 4.x, 3.x 2.x

  • Add .net dll OnBarcode.Barcode.BarcodeScanner.dll from {Download package}/dll/net40/ or /net20/ to your C# project reference




About trial version dll vs licensed dll

When you have downloaded and installed the free trial version of OnBarcode .NET Barcode Generator SDK, you will get all almost exactly same features as the licensed dll.

There is only one limit in the trial version of dll. The first character or digit from returned barcode data is randomly generated. In the licensed sdk, we have removed the limit.




Barcode Library all Supported Barcode Formats

public enum BarcodeType
{
    AustraliaPost = 0,        EAN8 = 7,                 ITF14 = 14,          RM4SCC = 21,    
    Codabar = 1,              EAN13 = 8,                Leitcode = 15,       UPCA = 22,   
    Code39 = 2,               Identcode = 9,            PatchCode = 16,      UPCE = 23,    
    Code39Extension = 3,      IntelligentMail = 10,     PDF417 = 17,         All = 999   
    Code93 = 4,               Interleaved2of5 = 11,     Planet = 18,                   
    Code128 = 5,              ISBN = 12,                Postnet = 19,
    DataMatrix = 6,           ISSN = 13,                QRCode = 20,                               
}




Quick to start using C# barcode reader library

Read barcodes from image file

  • Use method BarcodeScanner.Scan() to read all barcodes from an image file

string[] datas = BarcodeScanner.Scan("code128-barcode.png", BarcodeType.Code128);

BarcodeDetail[] datasInDetail = BarcodeScanner.ScanInDetails(
    "code128-barcode.png", BarcodeType.Code128);



Read barcodes from Stream object

  • Use method BarcodeScanner.Scan() to read all barcodes from an image Stream object

string[] datas = BarcodeScanner.Scan(imageObject, BarcodeType.Code128);

BarcodeDetail[] datasInDetail = BarcodeScanner.ScanInDetails(
    imageObject, BarcodeType.Code128);


Improve barcode reading speed

To improve the barcode reading speed, call ScanSingleBarcode, if there is maximum one barcode per image.
  • Use method BarcodeScanner.ScanSingleBarcode() to read all barcodes from an image file

string[] barcodes = BarcodeScanner.ScanSingleBarcode(
    "code39-image.gif", BarcodeType.Code39); 




ScanOptions and BarcodeDetail in C#

In Barcode Reader C# library, you can customize the barcode scanning options through ScanOptions, and view scanned barcode information (including data message, barcode coordinates, rotation angle) in BarcodeDetail.


ScanOptions

Using ScanOptions in C# Barcode Reader library, you can easily customize the barcode reading options to enhance reading speed, improve recognition rate, such as multi-threading scanning.

List of options in ScanOptions
  • SetScanRegions(): enable to scan specified regions inside the image file. It will speed up the reading speed, and improve the reading accuracy. View more details: How to read barcodes from specified regions in image in C#?
  • SetMaxMultiThreadCount(): enable to scan barcodes using multi-threading in C#. View details here: How to scan, read barcodes in multithreading using C#?
  • ScanSingle: enable to scan maximum one barcode per image file. It will improve the reading speed, if there is only one barcode in one image file.
  • EnableGS1: enable to read and parse GS1 data elements from GS1 compatible barcodes, such as QR Code, Data Matrix, GS1-128, GS1 DataBar. More details, view here: How to read and parse GS1 barcode using C#?
  • ScanDirection: Specify the barcode library image scanning direction to speed up the barcode reading speed.
  • StepInterval: When defining the barcode search area, the scanning spacing is used, which indicates how many lines are scanned at a time.
  • ZoomRatio: Valid range: 0.2F - 5.0F. Default is 1.0F. Apply scanned image zooming.




BarcodeDetail

You can quickly get the scanned barcode data in string using the above methods. Sometimes you need scan and find the barcode location on the image file or read special data from barcodes, such as GS1 data message, barcode data in Structure Append mode.

We have provided the C# class BarcodeDetail to help get more information about the scanned barcode data. In class BarcodeDetail, we have provided useful properties and methods for each scanned barcodes.

  • Rotation: find the rotation angle about the scanned barcode.

  • X1, Y1, X2, Y2, X3, Y3, X4, Y4: 8 properties which define the scanned barcode region on the image file.

  • IsStructuredAppend: It is for QR Code and Data Matrix barcodes only. To identify whether the QR Code or Data Matrix barcode is in Structure Append mode. If so, you need combine the scanned barcode data with other barcodes from the same message. You can view the details here:
    How to read barcode data in Structure Append mode in C#.net?

  • IsGS1Compitable: It is for QR Code, Data Matrix and Code 128 barcodes only. To identify whether the found barcode is GS1 compatible. Know more information, view here:
    How to read GS1 barcode data using C#?

  • Method isMacroPDF417(): It is for PDF417 barcodes only. View more information about Macro PDF417 barcode reading in C#:
    How to read Macro PDF417 barcodes using C#?

  • Method GetDataBytes(). You can get the read barcode data in byte array.

  • Method GetMessage(), GetMessage(Encoding enc). You can get the scanned barcode data using default UTF8 encoding or your specified encoding format.


To scan and get more information about the barcode in C#

String folder = @"C:\Output\";
String[] sourceImageFiles = new String[] {
    folder + "SourceImage01.png",
    folder + "SourceImage02.png"
};
//  Initial a ScanOptions object for scanning DataMatrix.
ScanOptions options = new ScanOptions(BarcodeType.DataMatrix);
//  Scan a list of source image files
BarcodeDetail[] result = BarcodeScanner.Scan(sourceImageFiles, options);
foreach (BarcodeDetail obj in result)
{
    Console.WriteLine("Message: '" + obj.GetMessage() + "'");
    //  Show index and file path of the source image in the input array.
    //  SourceFilePath is empty if the input is file streams or Bitmap objects.
    Console.WriteLine(" Source: Index=" + obj.SourceIndex 
        + "; Source Path: " + obj.SourceFilePath);
}




Read barcodes with multiple formats in C#

Using C# Barcode Reader library, you can easily get all barcodes with the same barcode format from an image file or Stream object in C# code.

  • The C# example code below explains how to get all QR Code barcodes from a png image file using C#
string[] datas = BarcodeScanner.Scan("qrcode-barcode.png", BarcodeType.QRCode);


You can also easily get all barcodes with different barcode formats in C#. View the detailed C# source code here:
How to read barcodes with different formats using C#?




Read barcodes from specified image regions using C#

To improve the reading speed, the barcode reader library also supports scanning the partial area of the image.

  • Using the following C# code, the barcode library will scan the specified region in the image only, and return all QR Code barcodes from the target area.
List<SRegion> region = new List<SRegion>();
region.Add(new SRegion(0, 0, 50, 60));

string[] barcodes = BarcodeScanner.ScanRegions(
    "qrcode-barcodes.png", BarcodeType.QRCode, region);


You can view the detailed guide here:
How to scan barcodes from specified image regions using C#?




Improve barcode reading performance with defined scanning directions

The C# Barcode Reader library supports scanning barcode image with specified directions. In class ScanOptions, you can specify the barcode reader scanning directions through property ScanDirection

Available direction options in enum ScanDirectionType
  • Undefined. Default value is the same as All.
  • LeftToRight. The library will scan the barcode image from left to right.
  • TopToBottom. The library will scan the barcode image from top to bottom.
  • RightToLeft. The library will scan the barcode image from right to left.
  • BottomToTop. The library will scan the barcode image from bottom to top.
  • Horizontal. Scan the barcode image from left to right, and right to left.
  • Vertical. Scan the barcode image from top to bottom, and bottom to top.
  • All. The barcode reader sdk will scan the barcode image from 4 different directions. Left to right, right to left, top to bottom, and bottom to top.
The C# source code below explains how to scan a Code 128 barcode image with all four directions.
ScanOptions ops = new ScanOptions(BarcodeType.Code128);
ops.ScanDirection = ScanDirectionType.All;


Here we explain how to set barcode scanning with two directions, from left to right and top to bottom.
ops.ScanDirection = ScanDirectionType.LeftToRight | ScanDirectionType.TopToBottom;


Barcode scan directions performance testing



In the following demo barcode scanning testing, we will try to scan a Code 128 barcode image with four different direction combinations.

Here is the testing image. You can download the original image here.


  • ScanDirectionType.All. Scan bacode with all four different directions.
  • ScanDirectionType.Horizontal. Scan barcode with two directions: from left to right, and from right to left.
  • ScanDirectionType.LeftToRight. Scan with one direction only, from left to right.
  • ScanDirectionType.LeftToRight | ScanDirectionType.TopToBottom. Scan with two diretions, from left to right, from top to bottom.
private static void readBarcodeSingleRound()
{
    ScanOptions ops = new ScanOptions(BarcodeType.Code128);
    ops.ScanDirection = ScanDirectionType.All;
    //ops.ScanDirection = ScanDirectionType.Horizontal;
    //ops.ScanDirection = ScanDirectionType.LeftToRight;
    //ops.ScanDirection = ScanDirectionType.LeftToRight | ScanDirectionType.TopToBottom;
    BarcodeDetail[] result = BarcodeScanner.Scan(
        "C:\\Input\\barcode-code128-demo-image.png", ops);
    if (result.Length > 0)
    {
         Debug.WriteLine("Count: " + result.Length);
         foreach (BarcodeDetail b in result)
         Debug.WriteLine("Message: '{0}'", b.GetMessage());
     }
     else
         Debug.WriteLine("No Barcode Found.");
}


We will repeat the above method 10 times using the following C# codes.
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
for (int round = 0; round < 10; round++)
    readBarcodeSingleRound();
float totalTime = (float)sw.ElapsedMilliseconds / 1000F;
Debug.WriteLine("Time: {0:F3}s; Ave.: {1:F3}s", totalTime, totalTime / 10F);


The barcode scanning results

ScanDirectionType.All ScanDirectionType.LeftToRight
|
ScanDirectionType.TopToBottom
ScanDirectionType.LeftToRight ScanDirectionType.Horizontal


Now we analyze the scanning results.
  • Based on the rotation angle, the appropriate scanning direction needs to be selected for barcode recognition.

    For example, a bsarcode that has not been rotated requires the Left to Right scanning direction for recognition; a barcode rotated by 90 degrees needs the Top to Bottom scanning direction.

  • Generally speaking, the more scanning directions are selected, the longer the time will be consumed.

    For instance, using Horizontal will scan in two directions, taking more time than one direction LeftToRight (0.205s vs 0.150s)

  • The main time consumption lies in the inspection and identification of candidate barcodes.

    For example, scanning LeftToRight and TopToBottom can identify two Code 128 barcodes, with a time consumption of 0.235s, which is greater than 0.205s (Horizontal). While scanning all four directions takes 0.241s, which is not significantly different from 0.235s.




Apply barcode image scanning step interval

When the C# Barcode Reader library scans barcodes from a raster image file, it will scan image pixels one line by one line. You can use property StepInterval in class ScanOptions to control the scanning step interval.

  • StepInterval: Specify the scanning spacing, which indicates how many lines are scanned at a time.
    The minimum value is 1, and every row will be scanned.
    Default value: 5 (scan once every 5 lines)
We will use the C# sample codes above, and update the scan options with the following codes.
ScanOptions ops = new ScanOptions(BarcodeType.Code128);
ops.ScanDirection = ScanDirectionType.LeftToRight;
ops.StepInterval = 5; // Default
//ops.StepInterval = 1;
//ops.StepInterval = 10;
//ops.StepInterval = 83;


Scan result and analysis

Here are the barcode scanning results with different step intervals applied in C# codes.

StepInterval = 1 StepInterval = 5
StepInterval = 10 StepInterval = 83


Now we analyze the scanning results with step interval applied
  • When searching for a barcode, a larger interval (assuming all other conditions are the same) usually results in less time consumption.

    For example, scanning each pixel line versus scanning every 5 lines, the time consumption comparison is 0.257s vs 0.151s.

  • If the spacing is too large, the barcode may be skipped, resulting in no barcodes detected from the image. (Whether it will be skipped depends on two factors: the height and position of the barcode.).

    For example, the demo image uses StepInterval = 83 for scanning, and the barcode library cannot detect the barcode.




Improve barcode recognition rate with image processing applied.

OnBarcode provide an image processing library to help improve barcode recognition rate in C# ASP.NET Core, web and Windows applications.

Fail to read barcode from the original image. Success to read barcode after dilate image processing applied.


You can learn more dilate image processing here: How to improve C# Barcode Reader recognition rate using dilate image processng?




Scan and Parse Complex Barcode Data Message

How to read ASCII non-printable characters from barcode image using C#?

QR Code, other 2D barcodes and Code 128 linear barcode supports ASCII chacters encoding. Some chars in ASCII are non-printable ones, which will not be displayed on the screen. When you use barcode reader software to scan barcode with non-printable chars encoded, you need process these chars specially.

Here is a Data Matrix barcode with non-printable char '[CR]' (carriage return) encoded using OnBarcode C# Barcode Generator library.


The C# codes below show how to scan and read ASCII non-printable text from barcode image using C# Barcode Reader library.
            string inputFilePath = "C://Input//csharp-datamatrix-none-printable-chars.png";

            // scan all data matrix symbols in the image file
            String[] result = BarcodeScanner.Scan(inputFilePath, BarcodeType.DataMatrix);

            if (result.Length > 0)
            {
                foreach (String msg in result)
                {
                    String tmp = msg.Replace("\r", "[CR]");
                    Debug.WriteLine("Barcode Message: '" + tmp + "'");
                }
            }
            else
            {
                Debug.WriteLine("No Barcode Found!");
            }

ASCII non-printable text cannot be printed on the screen directly, so we have replaced it with label '[CR]'.


You can also scan and parse the ASCII chars with its ASCII value.
String[] result = BarcodeScanner.Scan(bitmap, BarcodeType.DataMatrix);

if (result.Length > 0)
{
    foreach (String msg in result)
    {
        byte[] dataBytes = Encoding.ASCII.GetBytes(msg);
        Console.WriteLine("Show ASCII values: ");
        foreach (byte b in dataBytes)
        {
            char c = (char)b;
            if (c == '\r')
                c = ' ';
            Console.WriteLine("0x" + b.ToString("X2") + " -- " + c);
        }
    }
}

Here we have read and printed scanned barcode data each character with its ASCII value and char using method Encoding.ASCII.GetBytes() in C#.


Use ASCII Char Label for non-printing chars in C#

C# Barcode Reader library includes a simple method to scan and read all 128 ASCII characters from barcode. The non-printing chars in the barcode text will be expressed using ASCII char label defined in the ASCII table.

The C# sample code below will read all Code 128 barcodes from image file. And all non-printing chars in barcode Code 128 data will be expressed using ASCII char label. For example, ASCII character 'carriage return' will be express in scanned barcode data as '[CR]'. View detailed here: 33 non-printing ASCII characters.

            ScanOptions opts = new ScanOptions(BarcodeType.Code128);
            BarcodeDetail[] datas = BarcodeScanner.Scan("Code-128-sample.png", opts);

            foreach (BarcodeDetail obj in datas)
            {
                Console.WriteLine(" Barcode Text: " + obj.GetASCIITextMessage());
            }




How to read barcode with GS1 data in C#?

A GS1 data message contains a group data elements. Each element string is the combination of a GS1 Application Identifier (AI Code) and a GS1 Application Identifier data field (AI Data).

C# Barcode Reader library provides functions to read GS1 data string with GS1 function characters directly from barcode images.

View detailed C# example code here: How to read barcode with GS1 data in C#




How to read barcodes Structured Append data mode using C#?

Some barcodes (Such as QR Code, Data Matrix, PDF417) allow a data message to be encoded across multiple barcode symbols.

Up to 16 QR Code or Data Matrix symbols may be appended in a structured format.

View detailed C# example code here: How to read barcode with Structured Append mode in C#?




How to read barcode with Unicode text using C#?

Most barcode symbologies do not support encode Unicode text directly into barcode symbols. However 2d barcodes (Such as QR Code, Data Matrix, and PDF-417) usually support encoding byte array data message. C# developers could convert Unicode text into byte array, and encode the byte array into barcode symbols.

View detailed C# example code here: How to read barcode with Unicode text in C#?




Multi-threading in barcode scanning in C#



To improve the barcode scanning process speed, OnBarcode C# barcode reader library does support scanning multiple image files in multiple threads.

The C# sample source code shows how to scanning barcodes from mutliple image files in multi-thread programming.

  • Create a ScanOptions with barcode format to scane
  • Set maximum 3 threads through method SetMaxMultiThreadCount() in ScanOptions
  • Using Scan() method in BarcodeScanner to read barcodes customized with ScanOptions
            ScanOptions options = new ScanOptions(BarcodeType.QRCode);
            //  Set maximum number of threads could be used in the scanning.
            //  The valud must be non-negative.
            //  0: disable multi-thread (Default Value)
            //  >0: using multi-thread
            options.SetMaxMultiThreadCount(3);
            BarcodeDetail[] result = BarcodeScanner.Scan(
                new String[] {
                    "SourceImage01.png",
                    "SourceImage02.png",
                    "SourceImage03.png"
                }, options);

            foreach (BarcodeDetail obj in result)
            {
                //  Report result ... 
            }


You can view more detailed guide here: How to read, scan barcodes in multithreading using C#?




Read barcodes from imperfect images



Barcodes are compatible with ISO standards
You'd better use ISO standards fully compatible barcode generator to create barcodes. For example, ISO / IEC 18004 specifies that all valid QR Codes should have at least 10X margins (X is the QR module size).

Scan one barcode type at one time
Though Barcode reader sdk supports scanning multiple barcode types at one time, we still strongly recommend you to read, scan one barcode type at one time. Use multiple barcode types may lower the scan recognition ratio. For example, Code 39 and Code 128 are both linear barcodes. If you scan both barcode types at one time, and the scanned barcode image file is imperfect, you may get the wrong results.

Try to scan barcodes from specified regions of the image file
Some imperfect images may contain noises covered all area of the image. To get the scan result successflly, scan certain areas of the image is a useful method. View detailed C# code here:
How to scanned target areas in the image using C#




FAQs

Does barcode reader library support rotated barcodes reading and scanning?

Yes. The OnBarcode C# Barcode Reader library will automatically scan and detect rotated barcodes in .NET applications.



Can barcode scanner sdk recognize colored barcodes?

Yes. The barcode scanner sdk will handle QR Code and barcodes with different bar and space colors rendered.

Note: During colored barcode generation, you need choose right colors for barcode scanning. You can learn more details here: How to choose right colors for styled QR Code and barcodes?




Does barcode reader library support EAN/UPC add-on barcode decoding?

Yes. The barcode reader library will handle EAN/UPC add-on barcode automatically. The add-on code digits will be added to the main barcode data value.





































Terms of Use | Privacy Policy
Copyright © OnBarcode.com . All rights reserved.