VintaSoft Barcode .NET SDK 15.1: Документация для Веб разработчика
Распознавание штрих-кодов из изображения в приложении ASP.NET MVC5
Данное руководство демонстрирует, как создать пустое приложение ASP.NET MVC5 в Visual Studio .NET 2019 и распознать штрих-коды из изображения в приложении ASP.NET MVC5.

Вот шаги, которые необходимо выполнить:
  1. Создайте пустое приложение ASP.NET MVC5.

    Запустите Visual Studio .NET 2019 и создайте новый проект, тип проекта - веб-приложение ASP.NET. Включите в проекте использование .NET Framework 4.7.2:

    Выберите шаблон "Empty" для веб-приложения ASP.NET и включите в проекте использование Web API:

  2. Серверная сторона: Добавьте ссылки на сборки Vintasoft в приложение ASP.NET MVC5.

    Добавьте ссылки на сборки Vintasoft.Barcode.dll, Vintasoft.Shared.dll, Vintasoft.Shared.Web.dll, Vintasoft.Barcode.Web.Services.dll и Vintasoft.Barcode.Web.Api2Controllers.dll из папки "<InstallPath>\VintaSoft Barcode .NET 15.1\Bin\DotNet4\AnyCPU\" в приложение ASP.NET MVC5.

  3. Серверная сторона: Добавьте в приложение ASP.NET MVC5 контроллер Web API 2, который позволяет распознавать штрих-коды из изображения.

    • Нажмите правую кнопку мыши на папке "Controllers" и выберите "Add => Controller..." в контекстном меню
    • Выберите шаблон "Web API 2 Controller - Empty", задайте имя контроллера "MyVintasoftBarcodeApiController" и нажмите кнопку "Add"
    • Укажите, что класс MyVintasoftBarcodeApiController является производным от класса Vintasoft.Barcode.Web.Api2Controllers.VintasoftBarcodeApi2Controller

      Вот исходные коды C# класса MyVintasoftBarcodeApiController:
      using Vintasoft.Barcode.Web.Api2Controllers;
      
      namespace WebApplication1.Controllers
      {
          public class MyVintasoftBarcodeApiController : VintasoftBarcodeApi2Controller
          {
          }
      }
      
      
    • Откройте файл "App_Start\WebApiConfig.cs" и убедитесь, что приложение ASP.NET MVC корректно регистрирует маршрут для контроллера Web API.

      Вот исходные коды C# файла WebApiConfig.cs:
      using System.Web.Http;
      
      namespace WebApplication1
      {
          public static class WebApiConfig
          {
              public static void Register(HttpConfiguration config)
              {
                  config.Routes.MapHttpRoute(
                      name: "DemoAPI",
                      routeTemplate: "vintasoft/api/{controller}/{action}"
                  );
              }
          }
      }
      
      
  4. Серверная сторона: Создайте контроллер ASP.NET MVC 5 для веб-представления, которое будет отображать результат распознавания штрих-кодов.

    • Нажмите правую кнопку мыши на папке "Controllers" и выберите "Add => Controller..." в контекстном меню
    • Выберите шаблон "MVC 5 Controller - Empty", задайте имя контроллера "DefaultController" и нажмите кнопку "Add"
    • Откройте файл "App_Start\RouteConfig.cs" и убедитесь, что приложение ASP.NET MVC корректно регистрирует маршрут для контроллера MVC.

      Вот исходные коды C# файла RouteConfig.cs:
      using System.Web.Mvc;
      using System.Web.Routing;
      
      namespace WebApplication1
      {
          public class RouteConfig
          {
              public static void RegisterRoutes(RouteCollection routes)
              {
                  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
      
                  routes.MapRoute(
                      name: "Default",
                      url: "{controller}/{action}",
                      defaults: new { controller = "Default", action = "Index" }
                  );
      
              }
          }
      }
      
      
      
  5. Серверная сторона: Проверьте глобальную конфигурацию приложения ASP.NET MVC5.

    Откройте файл "Global.asax.cs" и убедитесь, что метод "Application_Start" регистрирует все области в приложении ASP.NET MVC, настраивает глобальную конфигурацию HTTP для приложения ASP.NET, регистрирует маршруты для приложения ASP.NET MVC.

    Вот исходные коды C# файла Global.asax.cs:
    using System.Web.Http;
    using System.Web.Mvc;
    using System.Web.Routing;
    
    namespace WebApplication1
    {
        public class WebApiApplication : System.Web.HttpApplication
        {
            protected void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();
                GlobalConfiguration.Configure(WebApiConfig.Register);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
            }
        }
    }
    
    
  6. Клиентская сторона: Создайте веб-представление для отображения результатов распознавания штрих-кодов.

    • Откройте файл "DefaultController.cs", нажмите правую кнопку мыши на методе "Index" класса DefaultController и выберите "Add View..." в контекстном меню
    • Задайте имя представления "Index", снимите флажок "Use a layout page" и нажмите кнопку "Add" => Будет создан файл "Views\Default\Index.cshtml"
  7. Клиентская сторона: Добавьте в проект файлы Vintasoft JavaScript.

    • Скопируйте файлы Vintasoft.Shared.js и Vintasoft.Barcode.js из папки "<InstallPath>\VintaSoft Barcode .NET 15.1\Bin\JavaScript\" в папку "Scripts".
  8. Клиентская сторона: Добавьте в веб-представление код JavaScript, который распознаёт штрих-коды из изображения и отображает результаты распознавания штрих-кодов.

    • Создайте папку "UploadedImageFiles\SessionID" и скопируйте в неё файл изображения со штрих-кодами "<InstallPath>VintaSoft\Barcode .NET 15.1\Images\AllSupportedBarcodes.png". Мы распознаем штрих-коды в этом изображении.
    • Откройте веб-представление - файл "Views\Default\Index.cshtml".
    • Добавьте ссылки на файлы Vintasoft JavaScript:

      Вот HTML-код, который добавляет ссылки на файлы Vintasoft JavaScript:
      <script src="~/Scripts/Vintasoft.Shared.js" type="text/javascript"></script>
      <script src="~/Scripts/Vintasoft.Barcode.js" type="text/javascript"></script>
      
      
    • Добавьте в веб-представление HTML-разметку (элемент div, который будет отображать результат распознавания штрих-кода):

      Вот код HTML-разметки:
      <div id="barcodeInformation"></div>
      
    • Добавьте код JavaScript, который распознаёт штрих-код из изображения и отображает результат распознавания штрих-кода:

      Вот код JavaScript, который распознаёт штрих-код из изображения и отображает результат распознавания штрих-кода:
      <script type="text/javascript">
      
          /**
           * Barcodes are recognized successfully.
           */
          function __readBarcodes_success(data) {
              if (data.success) {
                  // get the barcode recognition result
                  var barcodeRecognitionResults = data.results;
      
                  var htmlMarkup = '';
                  // if no barcodes found
                  if (barcodeRecognitionResults.length == 0) {
                      htmlMarkup = 'No barcodes found.';
                  }
                  // if barcodes are found
                  else {
                      htmlMarkup = barcodeRecognitionResults.length.toString() + ' barcodes are found.<br />';
                      htmlMarkup += '<br />';
      
                      // for each recognized barcode
                      for (var i = 0; i < barcodeRecognitionResults.length; i++) {
                          // get the barcode recognition result
                          var barcodeRecognitionResult = barcodeRecognitionResults[i];
      
                          // output information about recognized barcode
                          htmlMarkup += '[' + (i + 1) + ':' + barcodeRecognitionResult.barcodeType + ']<br />';
                          htmlMarkup += '  Value: ' + barcodeRecognitionResult.value + '<br />';
                          htmlMarkup += '  Confidence: ' + barcodeRecognitionResult.confidence + '<br />';
                          htmlMarkup += '  Reading quality: ' + barcodeRecognitionResult.readingQuality.toFixed(2) + '<br />';
                          htmlMarkup += '  Threshold: ' + barcodeRecognitionResult.threshold + '<br />';
                          htmlMarkup += '  Region: ' +
                              'LT=(' + barcodeRecognitionResult.region.leftTop.x + ',' + barcodeRecognitionResult.region.leftTop.y + '); ' +
                              'RT=(' + barcodeRecognitionResult.region.rightTop.x + ',' + barcodeRecognitionResult.region.rightTop.y + '); ' +
                              'LB=(' + barcodeRecognitionResult.region.leftBottom.x + ',' + barcodeRecognitionResult.region.leftBottom.y + '); ' +
                              'RB=(' + barcodeRecognitionResult.region.rightBottom.x + ',' + barcodeRecognitionResult.region.rightBottom.y + '); ' +
                              'Angle=' + barcodeRecognitionResult.region.angle.toFixed(1) + '°<br />';
      
                          htmlMarkup += '<br />';
                      }
                  }
      
                  var barcodeInformationElement = document.getElementById("barcodeInformation");
                  barcodeInformationElement.innerHTML = htmlMarkup;
              }
          }
      
          /**
           * Barcode recognition is failed.
           */
          function __readBarcodes_fail(data) {
              // show information about error
              alert(data.errorMessage);
          }
      
      
          // set the session identifier
          Vintasoft.Shared.WebImagingEnviromentJS.set_SessionId("SessionID");
      
          // create service that allows to recognize barcodes
          var barcodeService = new Vintasoft.Shared.WebServiceControllerJS("vintasoft/api/MyVintasoftBarcodeApi");
      
          // create the barcode reader
          var barcodeReader = new Vintasoft.Barcode.WebBarcodeReaderJS(barcodeService);
          // specify that Code39 barcode must be searched
          barcodeReader.get_Settings().set_BarcodeType(new Vintasoft.Barcode.WebBarcodeTypeEnumJS("Code39"));
      
          // create web image that references to a file "AllSupportedBarcodes.png" in directory "/UploadedImageFiles/SessionID/"
          var imageSource = new Vintasoft.Shared.WebImageSourceJS("AllSupportedBarcodes.png");
          var image = new Vintasoft.Shared.WebImageJS(imageSource, 0);
      
          // send an asynchronous request for barcode recognition
          barcodeReader.readBarcodes(image, this.__readBarcodes_success, this.__readBarcodes_fail);
      </script>
      
      
  9. Запустите приложение ASP.NET MVC5 и оцените результат.