在Blazor中使用IronBarcode
本操作指南包含如何在Blazor專案中整合IronBarcode的詳細指導。 作為範例,我們將在Blazor應用中使用IronBarcode來掃描從使用者網路攝影機捕獲的條形碼/QR碼。
如何在Blazor中使用條碼掃描器
- 安裝C#程式庫以在Blazor中掃描條碼
- 建立一個Blazor伺服器專案並新增一個新的Razor元件
- 使用JavaScript啟用網路攝影機
- 設定影像捕捉的方法以將圖像發送到伺服器
- 利用BarcodeReader.Read方法解碼條碼
建立Blazor專案
打開Visual Studio => 建立新專案 => Blazor伺服器應用:

設置專案名稱和位置:

選擇.NET 6框架(或任何其他現代標準.NET版本):

然後我們準備好:

要新增網路攝影機支持,請新增一個新的Razor元件:

給它命名,然後點擊新增:

使用JavaScript啟用網路攝影機功能
由於此應用需要使用者的網路攝影機,應在客戶端進行處理以保護隱私。 在專案中新增一個JavaScript文件來處理網路攝影機功能並將其命名為webcam.js:

不要忘記在index.html的引用:
<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);
}
}
我們需要開啟使用者的網路攝影機。 在頁面載入時,通過覆寫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
它處理從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 Function
IronBarcode提取捕捉的影像
將IronBarcode NuGet套件新增到伺服器專案:
dotnet add package IronBarCode
現在,在伺服器專案中,新增一個API方法來處理編碼圖像並提取條碼/QR值。 下面的程式碼為Blazor專案新增條碼讀取功能。 從掃描的圖像中,我們進行影像預處理並將其輸入到FromStream方法。 將Image物件傳入BarcodeReader類別的方法中,以掃描Blazor中的條碼。 然後,可以從BarcodeResult物件的Value屬性中存取得到的條碼值。
[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檔案來啟用網路攝像頭支持。該檔案應包含存取和流式傳輸網路攝像頭影片的函式,這些函式可以通過JS interop從Blazor調用。
存取網路攝像頭需要什麼JavaScript?
JavaScript應包含像initializeCamera()的函式,該函式使用navigator.mediaDevices.getUserMedia來請求攝像頭存取並將影片流傳輸到HTML影片元素。
如何在Blazor中捕捉和處理網路攝像頭的幀?
編寫一個JavaScript函式以捕捉當前影片幀,將其轉換為base64編碼的圖像,並通過Blazor的JS interop發送到C#方法。然後該C#方法可以處理該圖像以進行條碼讀取。
如何在Blazor專案中讀取條碼?
通過在伺服器端API方法中使用條碼程式庫的讀取器類來解碼base64圖像字串,從中提取條碼值來讀取條碼。
使用Blazor中的條碼程式庫有什麼前提條件?
確保您已設置Blazor伺服器專案、安裝必要的NuGet套件,並配置JavaScript以處理網路攝像頭輸入。您還需要為條碼程式庫提供有效的授權金鑰。
如何在Blazor中將捕捉的圖像發送到伺服器?
通過在JavaScript中使用DotNetObjectReference來調用C#方法並附帶圖像資料,將base64圖像字串發送給該方法。
此條碼程式庫能處理QR碼嗎?
是的,條碼程式庫可以在.NET應用,包括Blazor中建立、讀取和管理條碼和QR碼。
在哪可以找到使用條碼程式庫的範例Blazor專案?
一個使用條碼程式庫的範例Blazor專案可從文章結論部分提供的連結進行下載。
IronBarcode支援條碼的批量處理嗎?
是的,IronBarcode支援批量處理,允許開發人員在一次操作中生成或讀取多個條碼,提高大規模應用的效率。

