Multiple Uses of Barcode Reader SDK Powerful Toolkit - ByteScout
  • Home
  • /
  • Blog
  • /
  • Multiple Uses of Barcode Reader SDK Powerful Toolkit

Multiple Uses of Barcode Reader SDK Powerful Toolkit

In this tutorial, you will find out how Barcode Reader SDK can help you read barcodes from scanned documents, PDFs, images, or a webcam using C# source code.

Barcode Reader SDK is a complete toolkit working in C# and VB.NET to read all types of existing barcodes (1D and 2D) from PDF, images, or a live camera.

In this developer tutorial, you will find the list of C# source code samples demonstrating the following features of Barcode Reader SDK in C#:

  1. Set Orientation and Read Rotated Barcodes
  2. Decode Driver License Information (PDF417)
  3. Read Barcodes from a Live Video Cam
  4. Read Barcodes from PDF
  5. Read 50 QR Codes from Picture

Set Orientation and Read Rotated Barcodes

The following source code snippet can be used to run Barcode Reader SDK when reading rotated barcodes in C#.

C# Code Sample to Set Orientation and Read Rotated Barcodes

Just copy-paste the following C# source code to see the program in action.

Program.cs

      
using System; using System.IO; using Bytescout.BarCodeReader; namespace ReadRotatedBarcodes { class Program { const string ImageFile = "barcode_skewed2.png"; static void Main() { Console.WriteLine("Reading barcode(s) from image {0}", Path.GetFullPath(ImageFile)); Reader reader = new Reader(); reader.RegistrationName = "demo"; reader.RegistrationKey = "demo"; // Set barcode type to find reader.BarcodeTypesToFind.Code128 = true; // Set barcode Orientation // DiagonalFromTopLeftToBottomRight11 - Barcodes rotated clockwise by about 11 deg. reader.Orientation = OrientationType.DiagonalFromTopLeftToBottomRight11; /* ----------------------------------------------------------------------- NOTE: We can read barcodes from specific page to increase performance. For sample please refer to "Decoding barcodes from PDF by pages" program. ----------------------------------------------------------------------- */ // Read barcodes FoundBarcode[] barcodes = reader.ReadFrom(ImageFile); foreach (FoundBarcode barcode in barcodes) { Console.WriteLine("Found barcode with type '{0}' and value '{1}'", barcode.Type, barcode.Value); } // Cleanup reader.Dispose(); Console.WriteLine("Press any key to exit.."); Console.ReadKey(); } } }

ReadRotatedBarcodes.NETCore.csproj

      
<?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp2.0</TargetFramework> <EnableDefaultCompileItems>false</EnableDefaultCompileItems> <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> <GenerateAssemblyFileVersionAttribute>false</GenerateAssemblyFileVersionAttribute> <GenerateAssemblyInformationalVersionAttribute>false</GenerateAssemblyInformationalVersionAttribute> <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> <GenerateAssemblyTitleAttribute>false</GenerateAssemblyTitleAttribute> <GenerateAssemblyVersionAttribute>false</GenerateAssemblyVersionAttribute> <GenerateAssemblyCopyrightAttribute>false</GenerateAssemblyCopyrightAttribute> <GenerateAssemblyTrademarkAttribute>false</GenerateAssemblyTrademarkAttribute> <GenerateAssemblyCultureAttribute>false</GenerateAssemblyCultureAttribute> <GenerateAssemblyDescriptionAttribute>false</GenerateAssemblyDescriptionAttribute> </PropertyGroup> <ItemGroup> <Compile Include="Program.cs" /> <None Include="barcode_skewed2.png"> <CopyToOutputDirectory>Always</CopyToOutputDirectory> </None> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.Windows.Compatibility" Version="2.0.0" /> </ItemGroup> <ItemGroup> <Reference Include="Bytescout.BarCodeReader"> <SpecificVersion>False</SpecificVersion> <HintPath>c:\Program Files\Bytescout BarCode Reader SDK\netcoreapp2.0\Bytescout.BarCodeReader.dll</HintPath> </Reference> </ItemGroup> </Project>

Decode Driver License Information (PDF417)

The source code sample below can help you decode a PDF417 barcode (for example, driver license information) with Barcode Reader SDK in C#.

C# Code Sample to Decode PDF417 Barcode

Just use the C# source code below to run the program.

Program.cs

      
using System; using System.IO; using Bytescout.BarCodeReader; namespace ReadDriverLicenseInformation { class Program { // Replace barcode input file path here const string InputFile = "InputBarcodeImage.jpg"; static void Main() { Console.WriteLine("Reading barcode(s) from image {0}", Path.GetFullPath(InputFile)); Reader reader = new Reader(); reader.RegistrationName = "demo"; reader.RegistrationKey = "demo"; // Set barcode type to find reader.BarcodeTypesToFind.PDF417 = true; /* ----------------------------------------------------------------------- NOTE: We can read barcodes from specific page to increase performance. For sample please refer to "Decoding barcodes from PDF by pages" program. ----------------------------------------------------------------------- */ // Read barcodes FoundBarcode[] barcodes = reader.ReadFrom(InputFile); if(barcodes.Length > 0) { FoundBarcode barcode = barcodes[0]; // Get specific fields: IdentificationCard identificationCard = barcode.Metadata as IdentificationCard; if (identificationCard != null) { Console.WriteLine("ID Numer: " + identificationCard.IdNumber); Console.WriteLine("First Name: " + identificationCard.Name.First); Console.WriteLine("Middle Name: " + identificationCard.Name.Middle); Console.WriteLine("Last Name: " + identificationCard.Name.Last); Console.WriteLine("Sex: " + identificationCard.Sex); Console.WriteLine("Date Of Birth: " + identificationCard.DateOfBirth); Console.WriteLine("Address: " + identificationCard.Address); if (identificationCard is DriversLicense) { DriversLicense driverLicense = (DriversLicense)identificationCard; Console.WriteLine("Vehicle Class: " + driverLicense.Jurisdiction.VehicleClass); Console.WriteLine("Endorsement Codes: " + driverLicense.Jurisdiction.EndorsementCodes); Console.WriteLine("Restriction Codes: " + driverLicense.Jurisdiction.RestrictionCodes); } } else { Console.WriteLine("Could not retrieve AAMVA data from this barcode. Raw value: \r\n" + barcode.Value); } // ... or get the full information as JSON: Console.WriteLine("\n\n-----------------\n"); string jsonString = reader.ExportFoundBarcodesToJSON(); Console.WriteLine(jsonString); } else { Console.WriteLine("No barcodes found!"); } // Cleanup reader.Dispose(); Console.WriteLine("Press any key to exit.."); Console.ReadKey(); } } }

ReadDriverLicenseInformation.NETCore.csproj

      
<?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp2.0</TargetFramework> <EnableDefaultCompileItems>false</EnableDefaultCompileItems> <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> <GenerateAssemblyFileVersionAttribute>false</GenerateAssemblyFileVersionAttribute> <GenerateAssemblyInformationalVersionAttribute>false</GenerateAssemblyInformationalVersionAttribute> <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> <GenerateAssemblyTitleAttribute>false</GenerateAssemblyTitleAttribute> <GenerateAssemblyVersionAttribute>false</GenerateAssemblyVersionAttribute> <GenerateAssemblyCopyrightAttribute>false</GenerateAssemblyCopyrightAttribute> <GenerateAssemblyTrademarkAttribute>false</GenerateAssemblyTrademarkAttribute> <GenerateAssemblyCultureAttribute>false</GenerateAssemblyCultureAttribute> <GenerateAssemblyDescriptionAttribute>false</GenerateAssemblyDescriptionAttribute> </PropertyGroup> <ItemGroup> <Compile Include="Program.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.Windows.Compatibility" Version="2.0.0" /> </ItemGroup> <ItemGroup> <Reference Include="Bytescout.BarCodeReader"> <SpecificVersion>False</SpecificVersion> <HintPath>c:\Program Files\Bytescout BarCode Reader SDK\netcoreapp2.0\Bytescout.BarCodeReader.dll</HintPath> </Reference> </ItemGroup> </Project>

Read Barcodes from a Live Video Cam

The following source code snippet can be used to run Barcode Reader SDK when reading barcodes from a live webcam in C#.

C# Code Sample to Read Barcodes from a Web Camera

This C# source code sample can be used to run the program.

MainForm.cs

using System;
using System.ComponentModel;
using System.Drawing;
using System.Media;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using Bytescout.BarCodeReader;
using TouchlessLib;


namespace ReadFromVideoCamera
{
    public partial class MainForm: Form
    {
		// Scan delay, ms.
		const int SCAN_DELAY = 1500; // scan barcodes every 1.5 sec

		// Touchless SDK library manager (to use it you should have TouchlessLib.dll referenced and WebCamLib.dll in the build output directory)
	    readonly TouchlessMgr _touchlessLibManager;

        // Background thread for barcode scanning
        readonly BackgroundWorker _backgroundWorker = new BackgroundWorker();
		// Synchronization event
	    readonly AutoResetEvent _synchronizationEvent = new AutoResetEvent(false);
        
		// Form constructor
		public MainForm()
        {
            InitializeComponent();

            // Create Touchless library manager
            _touchlessLibManager = new TouchlessMgr();

			// Setup background worker
            _backgroundWorker.WorkerSupportsCancellation = true;
			_backgroundWorker.DoWork += BackgroundWorker_DoWork;
			_backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;
		}

	    // On form loading 
        private void Form_Load(object sender, EventArgs e)
        {
            // Fill devices combobox with available video cameras
            foreach (Camera camera in _touchlessLibManager.Cameras)
                cmbCamera.Items.Add(camera);

            // Select the first available camera. See also cmbCamera_SelectedIndexChanged event handler.
	        if (_touchlessLibManager.Cameras.Count > 0)
		        cmbCamera.SelectedItem = _touchlessLibManager.Cameras[0];
	        else
		        MessageBox.Show("No video camera available. Please connect the camera.");

	        // Populate barcode types combobox
            PopulateBarcodeTypesCombobox();
			// Select some default barcode type
			cmbBarcodeType.SelectedItem = "QRCode";
        }

	    protected void PopulateBarcodeTypesCombobox()
	    {
		    cmbBarcodeType.Items.Clear();

		    foreach (PropertyInfo propertyInfo in typeof(BarcodeTypeSelector).GetProperties())
			    cmbBarcodeType.Items.Add(propertyInfo.Name);
	    }
		
		// On camera selected
        private void cmbCamera_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_touchlessLibManager.CurrentCamera != null)
                _touchlessLibManager.CurrentCamera.OnImageCaptured -= CurrentCamera_OnImageCaptured;

			if (cmbCamera.SelectedIndex != -1)
			{
				Camera camera = _touchlessLibManager.Cameras[cmbCamera.SelectedIndex];

				if (camera != null)
				{
					// Set camera output image dimensions
					camera.CaptureWidth = int.Parse(tbCameraWidth.Text);
					camera.CaptureHeight = int.Parse(tbCameraHeight.Text);

					camera.OnImageCaptured += CurrentCamera_OnImageCaptured;

					// Select the camera
					_touchlessLibManager.CurrentCamera = camera;
				}
			}
        }

		private void btnUpdateCameraImageDimensions_Click(object sender, EventArgs e)
        {
            if (_touchlessLibManager.CurrentCamera != null)
            {
                // Update camera's output image dimensions
                _touchlessLibManager.CurrentCamera.CaptureWidth = int.Parse(tbCameraWidth.Text);
                _touchlessLibManager.CurrentCamera.CaptureHeight = int.Parse(tbCameraHeight.Text);
            }
        }

        public void StartDecoding()
        {
            if (cmbCamera.SelectedIndex == -1)
                return;

            // Clear the output text box
            rtbFoundBarcodes.Clear();

            // Check if we have camera selected
            if (cmbCamera.SelectedIndex != -1)
            {
				// Start the decoding in the background thread
	            BarcodeTypeSelector barcodeTypesToFind = GetBarcodeTypeFromCombobox();
	            _backgroundWorker.RunWorkerAsync(barcodeTypesToFind);

				UpdateControls(true);
			}
			else
            {
                MessageBox.Show("Please select the camera first!");
            }
        }

        private void StopDecoding()
        {
	        _backgroundWorker.CancelAsync();

			// Wait until BackgroundWorker finished
	        if (_backgroundWorker.IsBusy)
		        _synchronizationEvent.WaitOne();

	        UpdateControls(false);
        }

	    void UpdateControls(bool started)
	    {
		    if (started)
		    {
				btnStart.Enabled = false;
				btnStop.Enabled = true;
				cmbBarcodeType.Enabled = false;
				cmbCamera.Enabled = false;
			    tbCameraHeight.Enabled = false;
			    tbCameraWidth.Enabled = false;
			    btnUpdateCameraImageDimensions.Enabled = false;
			    cbStopOnFirstBarcode.Enabled = false;
			    lblScanning.Visible = true;
			    lblScanning.Text = "Scanning...";
		    }
		    else
		    {
				btnStart.Enabled = true;
				btnStop.Enabled = false;
				cmbBarcodeType.Enabled = true;
				cmbCamera.Enabled = true;
				cbStopOnFirstBarcode.Enabled = true;
				tbCameraHeight.Enabled = true;
				tbCameraWidth.Enabled = true;
				btnUpdateCameraImageDimensions.Enabled = true;
				lblScanning.Visible = true;
			}
	    }

        void CurrentCamera_OnImageCaptured(object sender, CameraEventArgs e)
        {
			pictureBoxPreview.Image = e.Image;
        }

	    private void btnStart_Click(object sender, EventArgs e)
        {
            StartDecoding();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            StopDecoding();
        }

        // Background thread procedure used by BackgroundWorker
		public void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
		{
			BackgroundWorker worker = (BackgroundWorker) sender;
			BarcodeTypeSelector barcodeTypesToFind = (BarcodeTypeSelector) e.Argument;

            // Create and setup barcode reader instance
			using (Reader reader = new Reader())
			{
				reader.RegistrationName = "demo";
				reader.RegistrationKey = "demo";

				reader.BarcodeTypesToFind = barcodeTypesToFind;

				// Work while not canceled
				while (true)
				{
					// Check cancellation
					if (worker.CancellationPending)
					{
						e.Cancel = true;
						_synchronizationEvent.Set();
						return;
					}

					// Get image from camera by invoking method from UI thread
					Bitmap bitmap = (Bitmap) Invoke(new GetCameraImageDelegate(GetCameraImage));
					if (bitmap == null)
					{
						e.Result = null;
						return;
					}

					// Search the image for barcodes
					FoundBarcode[] result = reader.ReadFrom(bitmap);

					// Update UI asynchronously
					BeginInvoke(new Action(UpdateStatus), new object[] { result });

					// Pause
					Thread.Sleep(SCAN_DELAY);
				}
			}
		}

		delegate Bitmap GetCameraImageDelegate();

	    Bitmap GetCameraImage()
	    {
			if (!IsDisposed && !Disposing && _touchlessLibManager.CurrentCamera != null)
				return _touchlessLibManager.CurrentCamera.GetCurrentImage();

		    return null;
	    }

		// Update UI with found barcodes information
		void UpdateStatus(FoundBarcode[] foundBarcodes)
	    {
			if (foundBarcodes != null && foundBarcodes.Length > 0)
			{
				// Play sound if we found any barcode
				SystemSounds.Beep.Play();

				StringBuilder stringBuilder = new StringBuilder();

				stringBuilder.AppendFormat("Time: {0:HH:mm:ss:tt}", DateTime.Now);
				stringBuilder.AppendLine();

				// Display found barcodes in the output text box
				foreach (FoundBarcode barcode in foundBarcodes)
				{
					stringBuilder.AppendFormat("Found barcode: {0} {1}", barcode.Type, barcode.Value);
					stringBuilder.AppendLine();
				}

				rtbFoundBarcodes.Text = stringBuilder.ToString();

				// Update status text with number of found barcodes
				lblFoundBarcodes.Text = string.Format("Found {0} barcodes:", foundBarcodes.Length);
			}

			// Make "Scanning..." label flicker.
			lblScanning.Visible = !lblScanning.Visible;
			lblScanning.Refresh();

			// Check if we need to stop on first barcode found
			if (cbStopOnFirstBarcode.Checked && foundBarcodes != null && foundBarcodes.Length > 0)
			{
				StopDecoding();
			}
		}

		// Background thread is finished
	    private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
	    {
			// Update UI asynchronously
			BeginInvoke(new Action(OnBackgroundWorkerFinished), new object[] { e });
	    }

	    void OnBackgroundWorkerFinished(RunWorkerCompletedEventArgs completedEventArgs)
	    {
			if (completedEventArgs.Cancelled)
			{
				lblScanning.Text = "Stopped";
			}
			else if (completedEventArgs.Error != null)
			{
				lblScanning.Text = "Error: " + completedEventArgs.Error.Message;
			}
			else
			{
				lblScanning.Text = "Done!";
			}

			UpdateControls(false);
		}

		// Gets selected barcode type
		private BarcodeTypeSelector GetBarcodeTypeFromCombobox()
		{
			BarcodeTypeSelector result = new BarcodeTypeSelector();

			string selectedBarcodeTypeName = (string) cmbBarcodeType.SelectedItem;

	        PropertyInfo propertyInfo = typeof(BarcodeTypeSelector).GetProperty(selectedBarcodeTypeName);
			propertyInfo.SetValue(result, true, null);

			return result;
        }

	    protected override void OnClosing(CancelEventArgs e)
        {
			StopDecoding();
			
			_touchlessLibManager.Dispose();

			base.OnClosing(e);
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
			DialogResult = DialogResult.OK;
            Close();
        }

		private void btnCameraProperties_Click(object sender, EventArgs e)
		{
			try
			{
				if (_touchlessLibManager.CurrentCamera != null)
					_touchlessLibManager.CurrentCamera.ShowPropertiesDialog(Handle);
			}
			catch (Exception exception)
			{
				MessageBox.Show(exception.Message);
			}
		}
    }
}

Program.cs

using System;
using System.Windows.Forms;

namespace ReadFromVideoCamera
{
    static class Program
    {
        /// 
        /// The main entry point for the application.
        /// 
        [MTAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            MainForm dlg = new MainForm();
            dlg.ShowDialog();
        }
    }
}

Video Tutorial

Read Barcodes from PDF

The following source code sample can be used to launch Barcode Reader SDK when reading barcodes from PDF.

C# Code Sample to Read Barcodes from PDF Files

Just copy-paste the following C# source code to see the program in action.

Program.cs

      
using System; using Bytescout.BarCodeReader; namespace BarcodesFromPDF { class Program { static void Main() { Reader reader = new Reader(); reader.RegistrationName = "demo"; reader.RegistrationKey = "demo"; // Limit search to 1-dimensional barcodes only (exclude 2D barcodes to speed up the processing). // Change to barcodeReader.BarcodeTypesToFind.SetAll() to scan for all supported 1D and 2D barcode types // or select specific type, e.g. barcodeReader.BarcodeTypesToFind.PDF417 = True reader.BarcodeTypesToFind.All1D = true; Console.WriteLine("Reading barcodes from PDF document..."); /* ----------------------------------------------------------------------- NOTE: We can read barcodes from specific page to increase performance. For sample please refer to "Decoding barcodes from PDF by pages" program. ----------------------------------------------------------------------- */ FoundBarcode[] barcodes = reader.ReadFrom("example.pdf"); foreach (FoundBarcode barcode in barcodes) { Console.WriteLine("Found barcode with type '{0}' and value '{1}' on page {2} at {3}", barcode.Type, barcode.Value, barcode.Page, barcode.Rect); } // Cleanup reader.Dispose(); Console.WriteLine(); Console.WriteLine("Press any key to continue."); Console.ReadKey(); } } }

Read 50 QR Codes from a Picture

The source code snippet below would be used to read QR codes from a picture in C# using Barcode Reader SDK.

C# Code Snippet to Read QR Codes from a Picture in C#

This C# source code snippet can be used to run the program.

Program.cs

      
using System; using Bytescout.BarCodeReader; namespace Read50QRCodesBarcocesFromPicture { class Program { static void Main(string[] args) { try { // Create and activate Bytescout.BarCodeReader.Reader instance using (Reader reader = new Reader("demo", "demo")) { // Set barcode type to find reader.BarcodeTypesToFind.QRCode = true; /* ----------------------------------------------------------------------- NOTE: We can read barcodes from specific page to increase performance. For sample please refer to "Decoding barcodes from PDF by pages" program. ----------------------------------------------------------------------- */ // Read barcodes FoundBarcode[] barcodes = reader.ReadFrom("50_QrCodes.png"); foreach (FoundBarcode code in barcodes) Console.WriteLine("Found barcode value: '{1}'", code.Type, code.Value); } } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine(); Console.WriteLine("Press any key to exit..."); Console.ReadLine(); } } }

The above code snippets demonstrate just a few of the multiple functions Barcode Reader SDK can offer. Check the documentation for more.

   

About the Author

ByteScout Team ByteScout Team of Writers ByteScout has a team of professional writers proficient in different technical topics. We select the best writers to cover interesting and trending topics for our readers. We love developers and we hope our articles help you learn about programming and programmers.  
prev
next