将 IronBarcode 与 Blazor 结合使用
这篇操作指南包含如何在 Blazor 项目中集成 IronBarcode 的详细说明。 作为示例,我们将在 Blazor 应用中使用 IronBarcode 扫描用户摄像头捕获的条形码/二维码。
如何在 Blazor 中使用条形码扫描器
- 安装C#库以在Blazor中扫描条形码
- 创建一个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>
将以下代码添加到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);
}
}
我们需要打开用户的摄像头。 在页面加载时,通过覆盖Index.razor的OnInitializedAsync()方法来执行此操作。 调用之前编写的JavaScript initializeCamera()函数。
protected override async Task OnInitializedAsync()
{
await JSRuntime.InvokeVoidAsync("initializeCamera");
}Protected Overrides Async Function OnInitializedAsync() As Task
Await JSRuntime.InvokeVoidAsync("initializeCamera")
End FunctionProtected Overrides Async Function OnInitializedAsync() As Task
Await JSRuntime.InvokeVoidAsync("initializeCamera")
End Function现在添加将运行摄像头视频流的 HTML 标签:
<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);
}
该函数将捕获一帧,将其编码为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(imageString As String) As Task
' Create an image object containing the base64 data
Dim imageObject As 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<JSInvokable>
Public Async Function ProcessImage(imageString As String) As Task
' Create an image object containing the base64 data
Dim imageObject As 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它负责将JavaScript中的getFrame()编码图像发送到服务器端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 FunctionPrivate Async Function CaptureFrame() As Task
Await JSRuntime.InvokeAsync(Of String)("getFrame", DotNetObjectReference.Create(Me))
End FunctionIronBarcode 提取捕获图像
将 IronBarcode NuGet 包添加到服务器项目中:
现在,在服务器项目中,添加一个 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);
var barcode = result.FirstOrDefault();
if (barcode == null || barcode.Value == null)
{
return $"{DateTime.Now}: Barcode is Not Detected";
}
return $"{DateTime.Now}: Barcode is ({barcode.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);
var barcode = result.FirstOrDefault();
if (barcode == null || barcode.Value == null)
{
return $"{DateTime.Now}: Barcode is Not Detected";
}
return $"{DateTime.Now}: Barcode is ({barcode.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(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)
Dim barcode = result.FirstOrDefault()
If barcode Is Nothing OrElse barcode.Value Is Nothing Then
Return $"{DateTime.Now}: Barcode is Not Detected"
End If
Return $"{DateTime.Now}: Barcode is ({barcode.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<HttpPost>
<Route("ReadBarCode")>
Public Function ReadBarCode(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)
Dim barcode = result.FirstOrDefault()
If barcode Is Nothing OrElse barcode.Value Is Nothing Then
Return $"{DateTime.Now}: Barcode is Not Detected"
End If
Return $"{DateTime.Now}: Barcode is ({barcode.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项目中集成IronBarcode?
要在Blazor项目中集成IronBarcode,您需要创建一个Blazor服务器应用程序,添加一个Razor组件来通过JavaScript启用网络摄像头功能,并利用IronBarcode的解码功能处理从摄像头捕获的图像。
IronBarcode可以用于在Blazor中扫描QR码吗?
是的,IronBarcode可以在Blazor项目中用于扫描QR码,使用网络摄像头捕获的图像,通过IronBarcode的BarcodeReader功能解码QR内容。
在Blazor应用程序中启用网络摄像头支持需要什么?
要在Blazor应用程序中启用网络摄像头支持,您需要添加一个JavaScript文件来管理网络摄像头功能,将其包含在您的项目中,并确保可以在客户端访问和处理网络摄像头的视频馈送。
在使用IronBarcode的Blazor应用中,条码处理是在客户端还是服务器端进行的?
在使用IronBarcode的Blazor应用中,条码处理是在服务器端进行的。图像通过客户端的JavaScript捕获后,会发送到服务器,在那里IronBarcode对其进行处理以解码条码。
在Blazor项目中捕获来自网络摄像头的帧的步骤是什么?
要捕获帧,请在您的JavaScript中添加一个函数,将当前帧绘制到画布上,将其转换为base64图像,然后将此数据发送到C#方法以进一步处理IronBarcode。
在Blazor IronBarcode集成中,'ProcessImage' C#方法的作用是什么?
'ProcessImage' C#方法接收来自JavaScript的base64编码图像数据,使用IronBarcode处理以解码条码,并与服务器端API交互以提取条码值。
IronBarcode在Blazor项目中如何授权?
IronBarcode需要在Blazor项目的服务器端代码中设置一个许可证密钥,以便在不受限制的情况下运行,确保条码功能能够正常执行。
如何在Blazor项目中安装IronBarcode?
可以通过在服务器项目中使用命令 'dotnet add package IronBarCode' 添加IronBarcode NuGet包的方式,在Blazor项目中安装IronBarcode。
在集成IronBarcode时,Blazor项目可以使用哪些框架版本?
在为集成IronBarcode创建Blazor项目时,您可以使用.NET 6或任何其他现代标准.NET版本作为项目框架。
Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。