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

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

    Запустите Visual Studio .NET 2022 и создайте новый проект, тип проекта - веб-приложение ASP.NET Core:

    Включите в проекте использование .NET 8.0:

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

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

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

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

      Вот исходные коды класса MyVintasoftBarcodeApiController:
      using Microsoft.AspNetCore.Hosting;
      using Microsoft.AspNetCore.Mvc;
      using Vintasoft.Barcode.AspNetCore.ApiControllers;
      
      namespace WebApplication1.Controllers
      {
          public class MyVintasoftBarcodeApiController : VintasoftBarcodeApiController
          {
      
              public MyVintasoftBarcodeApiController(IWebHostEnvironment hostingEnvironment)
                  : base(hostingEnvironment)
              {
              }
      
          }
      }
      
      
  4. Серверная сторона: Добавьте Newtonsoft JSON для десериализации результатов распознавания штрих-кодов.

    • Добавьте ссылку на NuGet-пакет "Microsoft.AspNetCore.Mvc.NewtonsoftJson":
  5. Серверная сторона: Создайте контроллер MVC для веб-представления, которое будет отображать результат распознавания штрих-кода.

    • Нажмите правую кнопку мыши на папке "Controllers" и выберите "Add => Controller..." в контекстном меню
    • Выберите шаблон "MVC Controller - Empty", задайте имя контроллера "HomeController" и нажмите кнопку "Add"
    • Откройте файл "Program.cs", добавьте контроллеры с представлениями и форматировщики Newtonsoft.Json в сервисы приложения ASP.NET Core:

      Добавьте созданный контроллер MVC к конечным точкам приложения ASP.NET Core:

      Вот исходные коды C# файла Program.cs:
      var builder = WebApplication.CreateBuilder(args);
      
      // Add services to the container.
      builder.Services.AddRazorPages();
      builder.Services.AddControllersWithViews().AddNewtonsoftJson();
      
      var app = builder.Build();
      
      app.UseHttpsRedirection();
      app.UseStaticFiles();
      
      app.UseRouting();
      
      app.UseEndpoints(endpoints =>
      {
          endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
      });
      
      app.MapRazorPages();
      
      app.Run();
      
      
  6. Клиентская сторона: Создайте веб-представление для отображения результата распознавания штрих-кода.

    • Откройте файл "HomeController.cs", нажмите правую кнопку мыши на методе "Index" класса HomeController и выберите "Add View..." в контекстном меню
    • Выберите шаблон "Razor View - Empty", нажмите кнопку "Add", задайте имя представления "Index" и нажмите кнопку "Add" => Будет создан файл "Views\Home\Index.cshtml"
  7. Клиентская сторона: Добавьте в проект файлы Vintasoft JavaScript.

    • Добавьте папку "wwwroot\Scripts\" в приложение ASP.NET Core.

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

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

      Вот базовый HTML-код:
      @{
          Layout = null;
      }
      
      <html>
      <head>
          <meta name="viewport" content="width=device-width" />
          <title>ASP.NET Core Barcode Generator Demo</title>
      
      </head>
      <body>
      
      </body>
      </html>
      
      
    • Добавьте ссылки на файлы 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>
      
      
    • Удалите папку "Pages".
  9. Запустите приложение ASP.NET Core и оцените результат.