Распознавание штрих-кодов на изображениях в приложении ASP.NET Core
В этом разделе
Данное руководство демонстрирует, как создать пустое веб-приложение ASP.NET Core в Visual Studio .NET 2026 и распознать штрих-коды в изображении в приложении ASP.NET Core.
Вот шаги, которые необходимо выполнить:
-
Создайте пустое веб-приложение ASP.NET Core.
Откройте Visual Studio .NET 2026 и создайте новый проект приложения типа "ASP.NET Core Web App (Model-View-Controller)":
Настройте проект для использования .NET 10.0:
-
Серверная сторона: Добавьте ссылки на nuget-пакеты Vintasoft в приложение ASP.NET Core.
Добавьте ссылки на nuget-пакеты "Vintasoft.Barcode", "Vintasoft.Barcode.SkiaSharp" и "Vintasoft.Barcode.AspNetCore.ApiControllers" в проект ASP.NET Core.
-
Серверная часть: Добавьте контроллер Web API, который позволяет распознавать штрих-коды в изображении.
-
Нажмите правую кнопку мыши на папке "Controllers" и выберите "Add => Controller..." в контекстном меню
-
Выберите пустой шаблон API-контроллера, задайте имя контроллера как "MyVintasoftBarcodeApiController" и нажмите кнопку "Добавить".
-
Укажите, что класс MyVintasoftBarcodeApiController является производным от класса Vintasoft.Barcode.AspNetCore.ApiControllers.VintasoftBarcodeApiController.
Вот исходный код класса MyVintasoftBarcodeApiController:
using Vintasoft.Barcode.AspNetCore.ApiControllers;
namespace WebApplication1.Controllers
{
public class MyVintasoftBarcodeApiController : VintasoftBarcodeApiController
{
public MyVintasoftBarcodeApiController(IWebHostEnvironment hostingEnvironment)
: base(hostingEnvironment)
{
}
}
}
-
Серверная сторона: Добавьте ссылку на nuget-пакет "Microsoft.AspNetCore.Mvc.NewtonsoftJson" для десериализации результатов распознавания штрих-кодов.
-
Добавить ссылку на nuget-пакет "Microsoft.AspNetCore.Mvc.NewtonsoftJson" в проект ASP.NET Core:
-
Откройте файл "Program.cs" и добавьте строку кода "builder.Services.AddControllersWithViews().AddNewtonsoftJson();". Это необходимо для корректной десериализации результатов распознавания штрих-кодов.
Вот исходный код файла Program.cs:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews().AddNewtonsoftJson();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// 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.UseRouting();
app.UseAuthorization();
app.MapStaticAssets();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}")
.WithStaticAssets();
app.Run();
-
Клиентская сторона: Добавьте в проект файлы Vintasoft JavaScript.
-
Добавьте папку "wwwroot\lib\Vintasoft" в приложение ASP.NET Core.
-
Скопируйте файлы Vintasoft.Shared.js и Vintasoft.Barcode.js из папки "\VintaSoft Barcode .NET 15.3\Bin\JavaScript" в папку "wwwroot\lib\Vintasoft".
-
Клиентская часть: Добавьте в веб-представление код JavaScript, который распознает штрих-коды в изображении и отобразит результат распознавания штрих-кодов.
-
Создайте папку "wwwroot\UploadedImageFiles\SessionID" и скопируйте в нее файл изображения с штрих-кодами "VintaSoft\Barcode .NET 15.3\Images\AllSupportedBarcodes.png". Мы будем распознавать штрих-коды в этом изображении.
-
Откройте файл "Views\Home\Index.cshtml", очистите файл, добавьте HTML-код (ссылки на файлы JavaScript VintaSoft; DIV-элемент, который будет отображать информацию о распознанных штрих-кодах) в файл "Index.cshtml":
Вот HTML-код файла "Index.cshtml":
@{
ViewData["Title"] "blue">Title"] = "Home Page";
}
<script src="~/lib/Vintasoft/Vintasoft.Shared.js" type="text/javascript"></script>
<script src="~/lib/Vintasoft/Vintasoft.Barcode.js" type="text/javascript"></script>
<div id="barcodeInformation"></div>
-
Откройте файл "wwwroot\js\site.js", очистите файл, добавьте JavaScript-код (распознает штрих-коды в изображении и отобразит результат распознавания штрих-кодов) в файл "site.js":
Вот код JavaScript, который распознаёт штрих-код из изображения и отображает результат распознавания штрих-кода:
/**
* Recognizes barcodes.
*/
function __recognizeBarcodes() {
// 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, __recognizeBarcodes_success, __recognizeBarcodes_fail);
}
/**
* Barcodes are recognized successfully.
*/
function __recognizeBarcodes_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 __recognizeBarcodes_fail(data) {
// show information about error
alert(data.errorMessage);
}
// recognize barcodes
__recognizeBarcodes();
-
Запустите приложение ASP.NET Core и посмотрите результат.