How to Use Barcode Scanner in Blazor | IronBarcode

将 IronBarcode 与 Blazor 结合使用

This article was translated from English: Does it need improvement?
Translated
View the article in English

这篇操作指南包含如何在 Blazor 项目中集成 IronBarcode 的详细说明。 作为示例,我们将在 Blazor 应用中使用 IronBarcode 扫描用户摄像头捕获的条形码/二维码。

创建 Blazor 项目

打开 Visual Studio => 创建新项目 => Blazor 服务器应用:

CreateBlazorProject related to 创建 Blazor 项目

设置项目名称和位置:

ProjectName related to 创建 Blazor 项目

选择 .NET 6 框架(或其他现代标准 .NET 版本):

SelectFramework related to 创建 Blazor 项目

一切准备就绪:

MainScreen related to 创建 Blazor 项目

要添加摄像头支持,添加一个新的 Razor 组件:

NewRazorComponent related to 创建 Blazor 项目

给它起个名字,然后点击 Add

NewRazorComponentName related to 创建 Blazor 项目

使用 JavaScript 启用摄像头功能

由于该应用正在使用用户的摄像头,因此应在客户端上进行处理以保护隐私。 向项目中添加一个用于处理网络摄像头功能的 JavaScript 文件,并将其命名为 webcam.js

JavascriptFileLocation related to 使用 JavaScript 启用摄像头功能

请务必在 index.html 中包含对 webcam.js 的引用:

<script src="webcam.js"></script>
<script src="webcam.js"></script>
HTML

请将以下代码添加到 webcam.js 中:

// Current video stream
let videoStream;

// Function to initialize camera access and stream it to a video element
async function initializeCamera() {
    const canvas = document.querySelector("#canvas");
    const video = document.querySelector("#video");

    // Check if navigator supports media devices
    if (!("mediaDevices" in navigator) || !("getUserMedia" in navigator.mediaDevices)) {
        alert("Camera API is not available in your browser");
        return;
    }

    // Define video constraints
    const constraints = {
        video: {
            width: { min: 180 },
            height: { min: 120 }
        },
    };

    // Set camera facing mode: "user" for front camera, "environment" for back camera
    constraints.video.facingMode = useFrontCamera ? "user" : "environment";

    try {
        // Request camera access
        videoStream = await navigator.mediaDevices.getUserMedia(constraints);
        video.srcObject = videoStream;
    } catch (err) {
        alert("Could not access the camera: " + err);
    }
}
// Current video stream
let videoStream;

// Function to initialize camera access and stream it to a video element
async function initializeCamera() {
    const canvas = document.querySelector("#canvas");
    const video = document.querySelector("#video");

    // Check if navigator supports media devices
    if (!("mediaDevices" in navigator) || !("getUserMedia" in navigator.mediaDevices)) {
        alert("Camera API is not available in your browser");
        return;
    }

    // Define video constraints
    const constraints = {
        video: {
            width: { min: 180 },
            height: { min: 120 }
        },
    };

    // Set camera facing mode: "user" for front camera, "environment" for back camera
    constraints.video.facingMode = useFrontCamera ? "user" : "environment";

    try {
        // Request camera access
        videoStream = await navigator.mediaDevices.getUserMedia(constraints);
        video.srcObject = videoStream;
    } catch (err) {
        alert("Could not access the camera: " + err);
    }
}
JAVASCRIPT

我们需要打开用户的摄像头。 页面加载时,请通过重写 OnInitializedAsync()Index.razor 方法来实现此功能。 调用您之前编写的 JavaScript initializeCamera() 函数。

protected override async Task OnInitializedAsync()
{
    await JSRuntime.InvokeVoidAsync("initializeCamera");
}
protected override async Task OnInitializedAsync()
{
    await JSRuntime.InvokeVoidAsync("initializeCamera");
}
Protected Overrides Async Function OnInitializedAsync() As Task
	Await JSRuntime.InvokeVoidAsync("initializeCamera")
End Function
$vbLabelText   $csharpLabel

现在添加将运行摄像头视频流的 HTML 标签:

<section class="section">
    <video autoplay id="video" width="320"></video>
</section>
<section class="section">
    <video autoplay id="video" width="320"></video>
</section>
HTML

捕获图像

要从网络摄像头视频流中捕获一帧画面,让我们在 webcam.js 中编写另一个 JavaScript 函数。 该函数将当前帧从源视频绘制到画布目标。

// Function to capture a frame from the video and send it to the server via Blazor
function getFrame(dotNetHelper) {
    // Set canvas dimensions to match video
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;

    // Draw the current video frame onto the canvas
    canvas.getContext('2d').drawImage(video, 0, 0);

    // Convert the canvas content to a base64 encoded PNG image
    let dataUrl = canvas.toDataURL("image/png");

    // Send the image data to the C# method `ProcessImage`
    dotNetHelper.invokeMethodAsync('ProcessImage', dataUrl);
}
// Function to capture a frame from the video and send it to the server via Blazor
function getFrame(dotNetHelper) {
    // Set canvas dimensions to match video
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;

    // Draw the current video frame onto the canvas
    canvas.getContext('2d').drawImage(video, 0, 0);

    // Convert the canvas content to a base64 encoded PNG image
    let dataUrl = canvas.toDataURL("image/png");

    // Send the image data to the C# method `ProcessImage`
    dotNetHelper.invokeMethodAsync('ProcessImage', dataUrl);
}
JAVASCRIPT

该函数将捕获一个帧,将其编码为 base64,然后将编码后的图像发送给 C# 中的一个名为 ProcessImage() 的方法。 ProcessImage() 方法如下:该方法将编码后的图像发送至服务器端 API 进行处理。

[JSInvokable]
public async Task ProcessImage(string imageString)
{
    // Create an image object containing the base64 data
    var imageObject = new CamImage();
    imageObject.imageDataBase64 = imageString;

    // Serialize image object to JSON
    var jsonObj = System.Text.Json.JsonSerializer.Serialize(imageObject);

    // Send image data to server-side API for processing
    var barcodeeResult = await Http.PostAsJsonAsync("Ironsoftware/ReadBarCode", imageObject);
    if (barcodeeResult.StatusCode == System.Net.HttpStatusCode.OK)
    {
        QRCodeResult = await barcodeeResult.Content.ReadAsStringAsync();
        StateHasChanged();
    }
}
[JSInvokable]
public async Task ProcessImage(string imageString)
{
    // Create an image object containing the base64 data
    var imageObject = new CamImage();
    imageObject.imageDataBase64 = imageString;

    // Serialize image object to JSON
    var jsonObj = System.Text.Json.JsonSerializer.Serialize(imageObject);

    // Send image data to server-side API for processing
    var barcodeeResult = await Http.PostAsJsonAsync("Ironsoftware/ReadBarCode", imageObject);
    if (barcodeeResult.StatusCode == System.Net.HttpStatusCode.OK)
    {
        QRCodeResult = await barcodeeResult.Content.ReadAsStringAsync();
        StateHasChanged();
    }
}
<JSInvokable>
Public Async Function ProcessImage(ByVal imageString As String) As Task
	' Create an image object containing the base64 data
	Dim imageObject = New CamImage()
	imageObject.imageDataBase64 = imageString

	' Serialize image object to JSON
	Dim jsonObj = System.Text.Json.JsonSerializer.Serialize(imageObject)

	' Send image data to server-side API for processing
	Dim barcodeeResult = Await Http.PostAsJsonAsync("Ironsoftware/ReadBarCode", imageObject)
	If barcodeeResult.StatusCode = System.Net.HttpStatusCode.OK Then
		QRCodeResult = Await barcodeeResult.Content.ReadAsStringAsync()
		StateHasChanged()
	End If
End Function
$vbLabelText   $csharpLabel

它负责将 getFrame() 中通过 JavaScript 编码的图像发送至服务器端 API 进行处理。

接下来,我们需要在点击捕获画面按钮时调用此 JavaScript 函数。 请注意,我们的按钮正在寻找一个名为 CaptureFrame 的处理函数。

private async Task CaptureFrame()
{
    await JSRuntime.InvokeAsync<String>("getFrame", DotNetObjectReference.Create(this));
}
private async Task CaptureFrame()
{
    await JSRuntime.InvokeAsync<String>("getFrame", DotNetObjectReference.Create(this));
}
Private Async Function CaptureFrame() As Task
	Await JSRuntime.InvokeAsync(Of String)("getFrame", DotNetObjectReference.Create(Me))
End Function
$vbLabelText   $csharpLabel

IronBarcode 提取捕获图像

将 IronBarcode NuGet 包添加到服务器项目中:

dotnet add package IronBarCode

现在,在服务器项目中,添加一个 API 方法来处理编码图像并提取条码/二维码值。 以下代码为 Blazor 项目添加了条码读取功能。 从扫描的图像中,我们进行图像预处理,并将其输入到 FromStream 方法中。 将 Image 对象传递给 BarcodeReader 类中的方法,以在 Blazor 中扫描 BarCode。 然后可以从BarcodeResult对象的属性中访问结果条码值。

[HttpPost]
[Route("ReadBarCode")]
public string ReadBarCode(CamImage imageData)
{
    try
    {
        // Decode the base64 image data
        var splitObject = imageData.imageDataBase64.Split(',');
        byte[] imagebyteData = Convert.FromBase64String((splitObject.Length > 1) ? splitObject[1] : splitObject[0]);

        // Set IronBarcode license key (replace 'Key' with actual key)
        IronBarCode.License.LicenseKey = "Key";

        using (var ms = new MemoryStream(imagebyteData))
        {
            // Convert byte array to Image
            Image barcodeImage = Image.FromStream(ms);
            // Read barcode from Image
            var result = BarcodeReader.Read(barcodeImage);
            if (result == null || result.Value == null)
            {
                return $"{DateTime.Now}: Barcode is Not Detected";
            }

            return $"{DateTime.Now}: Barcode is ({result.Value})";
        }
    }
    catch (Exception ex)
    {
        return $"Exception: {ex.Message}";
    }
}

// Model to encapsulate the base64 image data
public class CamImage
{
    public string imageDataBase64 { get; set; }
}
[HttpPost]
[Route("ReadBarCode")]
public string ReadBarCode(CamImage imageData)
{
    try
    {
        // Decode the base64 image data
        var splitObject = imageData.imageDataBase64.Split(',');
        byte[] imagebyteData = Convert.FromBase64String((splitObject.Length > 1) ? splitObject[1] : splitObject[0]);

        // Set IronBarcode license key (replace 'Key' with actual key)
        IronBarCode.License.LicenseKey = "Key";

        using (var ms = new MemoryStream(imagebyteData))
        {
            // Convert byte array to Image
            Image barcodeImage = Image.FromStream(ms);
            // Read barcode from Image
            var result = BarcodeReader.Read(barcodeImage);
            if (result == null || result.Value == null)
            {
                return $"{DateTime.Now}: Barcode is Not Detected";
            }

            return $"{DateTime.Now}: Barcode is ({result.Value})";
        }
    }
    catch (Exception ex)
    {
        return $"Exception: {ex.Message}";
    }
}

// Model to encapsulate the base64 image data
public class CamImage
{
    public string imageDataBase64 { get; set; }
}
<HttpPost>
<Route("ReadBarCode")>
Public Function ReadBarCode(ByVal imageData As CamImage) As String
	Try
		' Decode the base64 image data
		Dim splitObject = imageData.imageDataBase64.Split(","c)
		Dim imagebyteData() As Byte = Convert.FromBase64String(If(splitObject.Length > 1, splitObject(1), splitObject(0)))

		' Set IronBarcode license key (replace 'Key' with actual key)
		IronBarCode.License.LicenseKey = "Key"

		Using ms = New MemoryStream(imagebyteData)
			' Convert byte array to Image
			Dim barcodeImage As Image = Image.FromStream(ms)
			' Read barcode from Image
			Dim result = BarcodeReader.Read(barcodeImage)
			If result Is Nothing OrElse result.Value Is Nothing Then
				Return $"{DateTime.Now}: Barcode is Not Detected"
			End If

			Return $"{DateTime.Now}: Barcode is ({result.Value})"
		End Using
	Catch ex As Exception
		Return $"Exception: {ex.Message}"
	End Try
End Function

' Model to encapsulate the base64 image data
Public Class CamImage
	Public Property imageDataBase64() As String
End Class
$vbLabelText   $csharpLabel

您可以在此处找到示例项目。

常见问题解答

如何在Blazor项目中集成条形码库?

要在Blazor项目中集成条形码库,请安装适当的NuGet包,设置一个Blazor服务器项目,使用JavaScript启用摄像头支持,捕获图像,并使用库的条形码读取方法解码它们。

如何在Blazor应用中启用摄像头支持?

通过在Blazor项目中添加一个JavaScript文件来启用摄像头支持。该文件应包含访问和流式传输摄像头视频的功能,可以通过Blazor中的JS互操作调用。

访问摄像头需要哪些JavaScript?

JavaScript应包括一个类似initializeCamera()的功能,该功能使用navigator.mediaDevices.getUserMedia请求摄像头访问,并将视频流到HTML视频元素。

如何在Blazor中捕获和处理摄像头的帧?

编写一个JavaScript函数来捕获当前视频帧,将其转换为base64编码的图像,并使用Blazor的JS互操作将其发送到C#方法。然后C#方法可以处理图像以进行条形码读取。

如何在Blazor项目中读取条形码?

您可以通过在服务器端API方法中解码base64图像字符串,使用条形码库的读取类从图像中提取条形码值来读取条形码。

在Blazor中使用条形码库的先决条件是什么?

确保您已设置Blazor服务器项目,安装了必要的NuGet包,并配置好JavaScript以处理摄像头输入。您还需要条形码库的有效许可证密钥。

如何在Blazor中将捕获的图像发送到服务器?

通过在JavaScript中使用DotNetObjectReference调用C#方法,将图像数据与base64图像字符串一起发送到服务器。

此条形码库可以处理QR码吗?

是的,该条形码库可以在包括Blazor在内的.NET应用中创建、读取和管理条形码和QR码。

我在哪里可以找到使用条形码库的示例Blazor项目?

可以从文章结论部分提供的链接下载使用条形码库的示例Blazor项目。

IronBarcode 支持批量处理条形码吗?

是的,IronBarcode支持批量处理,允许开发人员在一个操作中生成或读取多个条形码,提高大规模应用的效率。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。

准备开始了吗?
Nuget 下载 2,240,258 | 版本: 2026.5 just released
Still Scrolling Icon

还在滚动吗?

想快速获得证据? PM > Install-Package BarCode
运行示例 观看您的字符串变成 BarCode。