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


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

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

      Включите в проекте использование .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 v15.0\Bin\DotNet8\AnyCPU\" в веб-приложение ASP.NET Core.
    3. Серверная сторона: Добавьте контроллер Web API, который позволяет распознавать штрих-коды из изображения.

      • Нажмите правую кнопку мыши на папке "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 Project1.Controllers
        {
            public class MyVintasoftBarcodeApiController : VintasoftBarcodeApiController
            {
        
                public MyVintasoftBarcodeApiController(IWebHostEnvironment hostingEnvironment)
                    : base(hostingEnvironment)
                {
                }
        
            }
        }
        
    4. Серверная сторона: Добавьте Newtonsoft JSON для десериализации результатов распознавания штрих-кодов.

      Добавьте ссылку на NuGet-пакет "Microsoft.AspNetCore.Mvc.NewtonsoftJson":


      Откройте файл "Program.cs" и добавьте строку кода "builder.Services.AddControllersWithViews().AddNewtonsoftJson();". Это необходимо для корректной десериализации результатов распознавания штрих-кодов.

      Вот исходные коды Program.cs:
      var builder = WebApplication.CreateBuilder(args);
      
      // Add services to the container.
      
      builder.Services.AddControllersWithViews().AddNewtonsoftJson();
      builder.Services.AddControllersWithViews();
      
      var app = builder.Build();
      
      // Configure the HTTP request pipeline.
      if (!app.Environment.IsDevelopment())
      {
          // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
          app.UseHsts();
      }
      
      app.UseHttpsRedirection();
      app.UseStaticFiles();
      app.UseRouting();
      
      
      app.MapControllerRoute(
          name: "default",
          pattern: "{controller}/{action=Index}/{id?}");
      
      app.MapFallbackToFile("index.html");
      
      app.Run();
      
      
    5. Скомпилируйте проект с помощью NPM - это нужно для восстановления зависимостей проекта.

    6. Клиентская сторона: Удалите файлы, которые не нужны в данной демонстрации.

      Удалите файлы "ClientApp\src\components\Counter.js", "ClientApp\src\components\FetchData.js", "ClientApp\src\components\Home.js", "ClientApp\src\components\NavMenu.js", "ClientApp\src\components\NavMenu.css" - эти компоненты React не нужны в данной демонстрации.

      Удалите файлы "WeatherForecast.cs" и "Controllers\WeatherForecastController.cs" - контроллер WeatherForecast Web API не нужен в этой демонстрации.


      Откройте файл "ClientApp\src\components\Layout.js" и удалите строки "import { NavMenu } from './NavMenu';" и "<NavMenu />" - в этой демонстрации нам не нужно навигационное меню.

      Откройте файл "ClientApp\src\App.js" и удалите код, использующий следующие компоненты React: Home, FetchData, Counter - эти компоненты React не нужны в данной демонстрации.
      Вот исходные коды файла "App.js" после обновления:
      import React, { Component } from 'react';
      import { Route } from 'react-router';
      import { Layout } from './components/Layout';
      
      import './custom.css'
      
      export default class App extends Component {
        static displayName = App.name;
      
        render () {
          return (
            <Layout>
            </Layout>
          );
        }
      }
      
    7. Клиентская сторона: Добавьте файлы JavaScript в веб-приложение ASP.NET Core.

      • Скопируйте файлы Vintasoft.Shared.js и Vintasoft.Barcode.js из папки "<InstallPath>\VintaSoft Barcode .NET v15.0\Bin\JavaScript\" в папку "ClientApp\public\".

      • Добавьте ссылки на файлы Vintasoft JavaScript в заголовок файла "ClientApp\public\index.html":
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
            <meta name="theme-color" content="#000000">
            <base href="%PUBLIC_URL%/" />
            <!--
              manifest.json provides metadata used when your web app is added to the
              homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
        -->
            <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
            <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
            <!--
              Notice the use of %PUBLIC_URL% in the tags above.
              It will be replaced with the URL of the `public` folder during the build.
              Only files inside the `public` folder can be referenced from the HTML.
        
              Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
              work correctly both with client-side routing and a non-root public URL.
              Learn how to configure a non-root public URL by running `npm run build`.
        -->
        
            <script src="Vintasoft.Shared.js" type="text/javascript"></script>
            <script src="Vintasoft.Barcode.js" type="text/javascript"></script>
        
            <title>WebApplication1</title>
        </head>
          <body>
            <noscript>
              You need to enable JavaScript to run this app.
            </noscript>
            <div id="root"></div>
            <!--
              This HTML file is a template.
              If you open it directly in the browser, you will see an empty page.
        
              You can add webfonts, meta tags, or analytics to this file.
              The build step will place the bundled scripts into the <body> tag.
        
              To begin the development, run `npm start` or `yarn start`.
              To create a production bundle, use `npm run build` or `yarn build`.
        -->
          </body>
        </html>
        

    8. Клиентская сторона: Создайте компонент React.js, который распознаёт штрих-коды из изображения и отображает результат распознавания штрих-кодов.

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

      • Создайте файл "BarcodeReaderDemo.js", который будет содержать исходные коды компонента React.js (класс BarcodeReaderDemo):
        • Выберите "Add => New Item..." в контекстном меню папки "ClientApp\src\components\" => Откроется диалог "Add new item"
        • Выберите тип нового элемента "JavaScript File"
        • Задайте имя элемента "BarcodeReaderDemo.js"
        • Нажмите кнопку "Add" => Диалог будет закрыт, а файл "BarcodeReaderDemo.js" будет добавлен в папку "ClientApp\src\components\"

        Добавьте в файл "BarcodeReaderDemo.js" декларацию класса BarcodeReaderDemo вместе с функцией "render" (рендерит заголовок страницы и элемент div, который будет отображать результат распознавания штрих-кодов):


        Добавьте в класс BarcodeReaderDemo функцию "componentDidMount" (содержит код JavaScript, который распознаёт штрих-код из изображения и отображает результат распознавания штрих-кодов):


        Вот код JavaScript компонента React.js (класс BarcodeReaderDemo):
        import React, { Component } from 'react';
        
        export class BarcodeReaderDemo extends Component {
            static displayName = BarcodeReaderDemo.name;
        
            render() {
                return (
                    <div>
                        <h1>React.js Barcode Reader Demo</h1>
        
                        <div id="barcodeInformation"></div>
                    </div>
                );
            }
        
            componentDidMount() {
                // declare reference to the Vintasoft namespace
                let Vintasoft = window.Vintasoft;
        
                // 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, __readBarcodes_success, __readBarcodes_fail);
        
        
                /**
                 * 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);
                }
        
            }
        
        }
        
      • Добавьте созданный компонент React.js в код приложения React.js - файл "ClientApp\src\App.js".


        Вот исходные коды файла "App.js" после обновления:
        import React, { Component } from 'react';
        import { Route } from 'react-router';
        import { Layout } from './components/Layout';
        import { BarcodeReaderDemo } from './components/BarcodeReaderDemo';
        
        import './custom.css'
        
        export default class App extends Component {
            static displayName = App.name;
        
            render() {
                return (
                    <Layout>
                        <Route exact path='/' component={BarcodeReaderDemo} />
                    </Layout>
                );
            }
        }
        
    9. Запустите веб-приложение ASP.NET Core на React.js и оцените результат.