将 IronBarcode 与 Blazor 结合使用
这篇操作指南包含如何在 Blazor 项目中集成 IronBarcode 的详细说明。 作为示例,我们将在 Blazor 应用中使用 IronBarcode 扫描用户摄像头捕获的条形码/二维码。
如何在 Blazor 中使用条形码扫描器
- 在 Blazor 中安装 C# 库以扫描条形码
- 创建一个Blazor服务器项目并添加一个新的Razor组件
- 使用JavaScript启用摄像头
- 配置图像捕获方法,将图像发送到服务器。
- 使用BarcodeReader.Read方法解码条形码
创建 Blazor 项目
打开 Visual Studio => 创建新项目 => Blazor 服务器应用:

设置项目名称和位置:

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

一切准备就绪:

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

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

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

别忘了在 index.html 中包含对webcam.js的引用:
<script src="webcam.js"></script><script src="webcam.js"></script>将以下代码添加到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);
}
}我们需要打开用户的摄像头。 通过覆盖Index.razor的OnInitializedAsync()方法,在页面加载时执行此操作。 调用你之前编写的 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现在添加将运行摄像头视频流的 HTML 标签:
<section class="section">
<video autoplay id="video" width="320"></video>
</section><section class="section">
<video autoplay id="video" width="320"></video>
</section>捕获图像
要从摄像头视频流中捕获画面,让我们在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);
}该函数将捕获一个帧,将其编码为 base64,然后将编码的图像发送到名为ProcessImage()的 C# 方法中。 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它负责将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 FunctionIronBarcode 提取捕获图像
将 IronBarcode NuGet 包添加到服务器项目中:
dotnet add package IronBarCode
现在,在服务器项目中,添加一个 API 方法来处理编码图像并提取条码/二维码值。 以下代码为 Blazor 项目添加了条码读取功能。 从扫描的图像中,我们进行图像预处理并将其输入到FromStream方法。 将图像对象传递到BarcodeReader类中的方法以在 Blazor 中扫描条码。 然后可以从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您可以在此处找到示例项目。
常见问题解答
如何在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项目。






