在 Blazor 中使用 IronBarcode
这篇说明文章包含如何在 Blazor 项目中集成 IronBarcode 的详细说明。 例如,我们将在 Blazor 应用程序中使用 IronBarcode 扫描从用户网络摄像头捕获的条形码/QR。
如何在 Blazor 中使用条码扫描器
- 在 Blazor 中安装 C# 库以扫描条形码
- 创建 Blazor 服务器项目并添加新的 Razor 组件
- 使用 JavaScript 启用网络摄像头
- 配置 图像采集 向服务器发送图像的方法
- 利用 BarCode 解码条形码 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;
async function initializeCamera()
{
const canvas = document.querySelector("#canvas");
const video = document.querySelector("#video");
if (
!"mediaDevices" in navigator
!"getUserMedia" in navigator.mediaDevices
)
{
alert("Camera API is not available in your browser");
return;
}
// video constraints
const constraints = {
video: {
width: {
min: 180
},
height: {
min: 120
},
},
};
constraints.video.facingMode = useFrontCamera ? "user" : "environment";
try
{
videoStream = await navigator.mediaDevices.getUserMedia (constraints);
video.srcObject = videoStream;
}
catch (err)
{
alert("Could not access the camera" + err);
}
}
我们需要打开用户的网络摄像头。 在页面加载时,通过覆盖 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
现在添加运行网络摄像头视频流的 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 getFrame(dotNetHelper)
{
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 0, 0);
let dataUrl = canvas.toDataURL("image/png");
//Invoke ProcessImage Function and send DataUrl as a parameter to it
dotNetHelper.invokeMethodAsync('ProcessImage', dataUrl);
}
该函数将捕获一帧图像,将其编码为 base64,然后将编码后的图像发送到 C# 中名为 "ProcessImage "的方法中。()`. 处理图像()方法如下:将编码后的图像发送到服务器端 API 进行处理。
[JSInvokable]
public async void ProcessImage(string imageString)
{
var imageObject = new CamImage();
imageObject.imageDataBase64 = imageString;
var jsonObj = System.Text.Json.JsonSerializer.Serialize(imageObject);
//Do image processing here
var barcodeeResult = await Http.PostAsJsonAsync($"Ironsoftware/ReadBarCode", imageObject);
if (barcodeeResult.StatusCode == System.Net.HttpStatusCode.OK)
{
QRCodeResult = barcodeeResult.Content.ReadAsStringAsync().Result;
StateHasChanged();
}
}
[JSInvokable]
public async void ProcessImage(string imageString)
{
var imageObject = new CamImage();
imageObject.imageDataBase64 = imageString;
var jsonObj = System.Text.Json.JsonSerializer.Serialize(imageObject);
//Do image processing here
var barcodeeResult = await Http.PostAsJsonAsync($"Ironsoftware/ReadBarCode", imageObject);
if (barcodeeResult.StatusCode == System.Net.HttpStatusCode.OK)
{
QRCodeResult = barcodeeResult.Content.ReadAsStringAsync().Result;
StateHasChanged();
}
}
<JSInvokable>
Public Async Sub ProcessImage(ByVal imageString As String)
Dim imageObject = New CamImage()
imageObject.imageDataBase64 = imageString
Dim jsonObj = System.Text.Json.JsonSerializer.Serialize(imageObject)
'Do image processing here
Dim barcodeeResult = Await Http.PostAsJsonAsync($"Ironsoftware/ReadBarCode", imageObject)
If barcodeeResult.StatusCode = System.Net.HttpStatusCode.OK Then
QRCodeResult = barcodeeResult.Content.ReadAsStringAsync().Result
StateHasChanged()
End If
End Sub
它将处理从 getFrame()将 JavaScript 中的
转换为服务器端 API 进行处理。
接下来,我们需要在点击 Capture Frame 按钮时调用 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
IronBarcode 提取捕获的图像
将 IronBarcode NuGet 软件包添加到服务器项目中:
Install-Package BarCode
现在,在服务器项目中,添加一个 API 方法来处理编码图像并提取 BarCode/QR 值。 下面的代码为 Blazor 项目添加了条形码读取功能。 我们对扫描图像进行图像预处理,并将其输入到 FromStream
方法中。 将图像对象传入 "BarcodeReader "类中的一个方法,以便在 Blazor 中扫描条形码。 然后,可从 BarcodeResult 对象的 Value 属性访问生成的条形码值。
[HttpPost]
[Route("ReadBarCode")]
public string ReadBarCode(CamImage imageData)
{
try
{
var splitObject = imageData.imageDataBase64.Split(',');
byte [] imagebyteData = Convert.FromBase64String((splitObject.Length > 1) ? splitObject [1] : splitObject [0]);
IronBarCode.License.LicenseKey = "Key";
using (var ms = new MemoryStream(imagebyteData))
{
Image barcodeImage = Image.FromStream(ms);
var result = BarcodeReader.Read(barcodeImage);
if (result == null
result.Value == null)
{
return $"{DateTime.Now} : Barcode is Not Detetced";
}
return $"{DateTime.Now} : Barcode is ({result.Value})";
}
}
catch (Exception ex)
{
return $"Exception is {ex.Message}";
}
}
//Post Object
public class CamImage
{
public string imageDataBase64 { get; set; }
}
[HttpPost]
[Route("ReadBarCode")]
public string ReadBarCode(CamImage imageData)
{
try
{
var splitObject = imageData.imageDataBase64.Split(',');
byte [] imagebyteData = Convert.FromBase64String((splitObject.Length > 1) ? splitObject [1] : splitObject [0]);
IronBarCode.License.LicenseKey = "Key";
using (var ms = new MemoryStream(imagebyteData))
{
Image barcodeImage = Image.FromStream(ms);
var result = BarcodeReader.Read(barcodeImage);
if (result == null
result.Value == null)
{
return $"{DateTime.Now} : Barcode is Not Detetced";
}
return $"{DateTime.Now} : Barcode is ({result.Value})";
}
}
catch (Exception ex)
{
return $"Exception is {ex.Message}";
}
}
//Post Object
public class CamImage
{
public string imageDataBase64 { get; set; }
}
<HttpPost>
<Route("ReadBarCode")>
Public Function ReadBarCode(ByVal imageData As CamImage) As String
Try
Dim splitObject = imageData.imageDataBase64.Split(","c)
Dim imagebyteData() As Byte = Convert.FromBase64String(If(splitObject.Length > 1, splitObject (1), splitObject (0)))
IronBarCode.License.LicenseKey = "Key"
Using ms = New MemoryStream(imagebyteData)
Dim barcodeImage As Image = Image.FromStream(ms)
Dim result = BarcodeReader.Read(barcodeImage)
If result Is Nothing result.Value Is Nothing Then
Return $"{DateTime.Now} : Barcode is Not Detetced"
End If
Return $"{DateTime.Now} : Barcode is ({result.Value})"
End Using
Catch ex As Exception
Return $"Exception is {ex.Message}"
End Try
End Function
'Post Object
Public Class CamImage
Public Property imageDataBase64() As String
End Class
您可以找到示例项目这里.