將 IronBarcode 與 Blazor 結合使用
本文詳細介紹如何在 Blazor 專案中整合 IronBarcode。 例如,我們將在 Blazor 應用程式中使用 IronBarcode 來掃描從用戶網路攝影機擷取的條碼/二維碼。
如何在 Blazor 中使用條碼掃描器
- 安裝C#程式庫以在Blazor中掃描條碼
- 創建一個 Blazor 伺服器專案並添加一個新的 Razor 元件
- 使用 JavaScript 啟用網路攝影機
- 配置圖片擷取方法以將圖片發送到伺服器
- 利用BarcodeReader.Read方法解碼條碼
建立 Blazor 項目
開啟 Visual Studio => 建立新專案 => Blazor 伺服器應用程式:

設定項目名稱和位置:

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

我們已準備就緒:

要新增相機支援,請新增一個新的 Razor 組件:

給它起個名字,然後點擊「新增」:

使用 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方法。 將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);
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檔案以管理網路攝影機功能,將其包含在專案中,並確保可以在客戶端存取和處理網路攝影機的視訊流。
在Blazor應用程式中使用IronBarcode時,條碼處理是在客戶端還是伺服器端進行的?
在Blazor應用程式中使用IronBarcode時,條碼處理是在伺服器端進行的。在客戶端使用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套件添加到伺服器專案中來安裝IronBarcode。
在整合IronBarcode時,Blazor專案可以使用哪些框架版本?
在為整合IronBarcode創建Blazor項目時,您可以使用.NET 6或任何其他現代Standard .NET版本作為項目的框架。
Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。