How to perform barcode recognition in C# with ABBYY Cloud OCR SDK

If you want to read barcodes in a C# application, first of all decide on the type of images you are going to process. Your images may contain only barcodes, or contain some other text together with barcodes. You might know barcode location on images beforehand, or the barcodes can be located anywhere on an image. When you are clear with these questions, you can select the way how to read barcodes in a C# application with ABBYY Cloud OCR SDK.

Cloud OCR SDK is provided in the form of Web API, which allows you, in particular, recognize barcodes. It can be easily used in C# application.

To use Cloud OCR SDK, you must be a registered user. You can register here. If you are a registered user, you have an Application ID and Application Password, which are passed to the processing server with each request. You can find more details in Authentication.

The procedure of recognition

But let's return to barcodes. There are two ways to read barcodes with Cloud OCR SDK:

  • The first one is perfect for the situation when you do not know exact location of barcodes on a page. In this case, you should use the processImage or processDocument method for recognition. You must specify the barcodeRecognition profile as a parameter in order barcodes can be extracted.
  • The second one is useful, when you are reading a single barcode value. In this case you can specify the type of the barcode and some additional parameters. See the description of the processBarcodeField method for details.

You can find more information on the parameters, which can be selected for processing using these methods, in How to Recognize Barcodes.

The procedures of recognition with any of the selected methods are very similar. Do the following:

  1. Call the selected method with necessary parameters and authentication data.
  2. The method returns response in XML format. See HTTP Status Codes and Response Formats.
  3. If the image is successfully submited, the response will contain the ID of the created task.
  4. Check the status of the task in a loop using the getTaskStatus method.
  5. When the task has the Completed status, you can download the result.

See details on the procedure in How to Work with Cloud OCR SDK.

Sample C# code

Below is the implementation of the procedure in C#. The sample code extracts barcode value from an image and saves results in an XML file.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Net;
using System.Xml;
using System.Xml.Linq;

static void Main(string[] args)
{
  // See implementation of the RestServiceClient class below
  RestServiceClient restClient = new RestServiceClient();
  restClient.Proxy.Credentials = CredentialCache.DefaultCredentials;
  // To use Cloud OCR SDK, you must be a registered user.
  // If you are not, 
  // register at http://cloud.ocrsdk.com/Account/Register
  // Create Application ID and Application Password for the application.
  // They can be created during registration.
  // Enter your data here.
  restClient.Password = "my_application_password";
  restClient.ApplicationId = "my_application_id";
  string sourcePath = "myfile.jpg";
  string targetPath = "output.xml";

  // To extract barcode values from an image,
  // send an image to Cloud OCR server using processImage call 
  // with barcodeRecognition profile as a parameter.
  Task task = restClient.ProcessImage(sourcePath);
  // See implementation of the Task class below

  // To read a single barcode field, 
  // send an image of a barcode to Cloud OCR server 
  // using processBarcodeField call:
  // Task task = restClient.ProcessBarcodeField(sourcePath);
  // See implementation of the Task class below

  string taskId = task.Id;

  while (true)
  {
    task = restClient.GetTaskStatus(taskId);
    if (!Task.IsTaskActive(task.Status))
      break;
    System.Threading.Thread.Sleep(1000);
  }

  if (task.Status == "Completed")
  {
    restClient.DownloadResult(task, targetPath);>

    // Parse output XML to extract barcode values.
    // Note that output XML files have different structure
    // depending on the method you used for processing.
 }
  else
  {
    // Error while processing the task.
  }
}

The implementation of the RestServiceClient class, used in the example above:

public class RestServiceClient
{
  public RestServiceClient()
  {
    ServerUrl = "http://cloud.ocrsdk.com/";
    Proxy = WebRequest.DefaultWebProxy;
  }

  public string ServerUrl { get; set; }
  public string ApplicationId { get; set; }
  public string Password { get; set; }

  public IWebProxy Proxy { get; set; }

  // Extracts barcode values from entire image.
  public Task ProcessImage(string filePath)
  {
    // Use barcodeRecognition profile to extract barcode values.
    // Save results in XML (you can use any other available output format).
    // For details, see API Reference for processImage method.
    string url = String.Format(
      "{0}/processImage?profile=barcodeRecognition&exportFormat=xml",
      ServerUrl);

    // Build post request.
    WebRequest request = WebRequest.Create(url);
    setupPostRequest(url, request);
    writeFileToRequest(filePath, request);

    XDocument response = performRequest(request);

    Task task = new Task();
    task.Id = response.Root.Element("task").Attribute("id").Value;
    task.Status = response.Root.Element("task").Attribute("status").Value;
    return task;
  }

  // Performs recognition of a barcode field.
  public Task ProcessBarcodeField(string filePath)
  {
    // Specify the region of a barcode (by default, the whole image is recognized), 
    // barcode type, and other parameters.
    // For details, see API Reference for processBarcodeField method.
    string url = String.Format(
      "{0}/processBarcodeField?region=0,0,100,100&barcodeType=pdf417",
      ServerUrl);

    // Build post request.
    WebRequest request = WebRequest.Create(url);
    setupPostRequest(url, request);
    writeFileToRequest(filePath, request);

    XDocument response = performRequest(request);
    Task task = new Task();
    task.Id = response.Root.Element("task").Attribute("id").Value;
    task.Status = response.Root.Element("task").Attribute("status").Value;
    return task;
  }

  private void setupPostRequest(string serverUrl, WebRequest request)
  {
    setupRequest(serverUrl, request);
    request.Method = "POST";
    request.ContentType = "application/octet-stream";
  }
  private void setupRequest(string serverUrl, WebRequest request)
  {
    if (Proxy != null)
    request.Proxy = Proxy;

    // Support authentication in case url is ABBYY SDK.
    if (serverUrl.StartsWith(ServerUrl, StringComparison.InvariantCultureIgnoreCase))
    {
      request.Credentials = new NetworkCredential(ApplicationId, Password);
    }
  }

  private void writeFileToRequest(string filePath, WebRequest request)
  {
    using (BinaryReader reader = new BinaryReader(File.OpenRead(filePath)))
    {
      request.ContentLength = reader.BaseStream.Length;
      using (Stream stream = request.GetRequestStream())
      {
        byte[] buf = new byte[reader.BaseStream.Length];
        while (true)
        {
          int bytesRead = reader.Read(buf, 0, buf.Length);
            if (bytesRead == 0)
            {
              break;
            }
            stream.Write(buf, 0, bytesRead);
          }
        }
      }
    }
    private XDocument performRequest(WebRequest request)
    {
      using (HttpWebResponse result = (HttpWebResponse)request.GetResponse())
      {
        using (Stream stream = result.GetResponseStream())
        {
          return XDocument.Load(new XmlTextReader(stream));
        }
      }
    }
  public Task GetTaskStatus(string task)
  {
    string url = String.Format("{0}/getTaskStatus?taskId={1}",
    ServerUrl, Uri.EscapeDataString(task));

    WebRequest request = WebRequest.Create(url);
    setupGetRequest(url, request);
    XDocument response = performRequest(request);
    Task serverTask = new Task();
    serverTask.Id = response.Root.Element("task").Attribute("id").Value;
    serverTask.Status = response.Root.Element("task").Attribute("status").Value;
    if (response.Root.Element("task").Attribute("resultUrl") != null)
    {
      serverTask.DownloadUrl = response.Root.Element("task").Attribute("resultUrl").Value;
    }
    return serverTask;
  }
  private void setupGetRequest(string serverUrl, WebRequest request)
  {
    setupRequest(serverUrl, request);
    request.Method = "GET";
  }

  // Download the resulting file and save it to given location.
  public void DownloadResult(Task task, string outputFile)
  {
    string url = task.DownloadUrl;
    WebRequest request = WebRequest.Create(url);
    setupGetRequest(url, request);
    using (HttpWebResponse result = (HttpWebResponse) request.GetResponse())
    {
      using (Stream stream = result.GetResponseStream())
      {
        // Write result directly to file.
        using (Stream file = File.OpenWrite(outputFile))
        {
          copyStream(stream, file); 
        }
      }
    }
  }

  private static void copyStream(Stream input, Stream output)
  {
    byte[] buffer = new byte[8 * 1024];
    int len;
    while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
    {
      output.Write(buffer, 0, len);
    }
  }
}

The implementation of the Task class:

public class Task
{
  public string Id;
  public string Status;

  // Url to download processed tasks.
  public string DownloadUrl = null;

  public Task()
  {
    Status = "<unknown>";
    Id = "<unknown>";
  }

  public Task(string id, string status)
  {
    Id = id;
    Status = status;
  }

  public bool IsTaskActive()
  {
    return IsTaskActive(Status);
  }

  // Task is submitted or is processing.
  public static bool IsTaskActive( string status )
  {
    if (status == "Submitted" ||
    status == "Queued" ||
    status == "InProgress")
    {
      return true;
    } else {
      return false;
    }
  }
}

This C# code for barcode reader is also available in the code samples provided with ABBYY Cloud OCR SDK. Also, you can find out how to read barcode in PHP with ABBYY Cloud OCR SDK.

Have more questions? Submit a request

Comments

0 comments

Please sign in to leave a comment.