如何在 Blazor | IronBarcode 中使用條碼掃描器

將 IronBarcode 與 Blazor 結合使用

This article was translated from English: Does it need improvement?
Translated
View the article in English

本文詳細介紹如何在 Blazor 專案中整合 IronBarcode。 例如,我們將在 Blazor 應用程式中使用 IronBarcode 來掃描從用戶網路攝影機擷取的條碼/二維碼。

建立 Blazor 項目

開啟 Visual Studio => 建立新專案 => Blazor 伺服器應用程式:

CreateBlazorProject related to 建立 Blazor 項目

設定項目名稱和位置:

ProjectName related to 建立 Blazor 項目

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

SelectFramework related to 建立 Blazor 項目

我們已準備就緒:

MainScreen related to 建立 Blazor 項目

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

NewRazorComponent related to 建立 Blazor 項目

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

NewRazorComponentName related to 建立 Blazor 項目

使用 JavaScript 啟用網路攝影機功能

由於此應用程式會使用使用者的網路攝影機,因此為了保護隱私,應在客戶端進行處理。 在專案中新增一個 JavaScript 檔案來處理相機功能,並將其命名為webcam.js

JavascriptFileLocation related to 使用 JavaScript 啟用網路攝影機功能

別忘了在index.html中加入對webcam.js的參考:

<script src="webcam.js"></script>
<script src="webcam.js"></script>
HTML

將以下程式碼加入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);
    }
}
JAVASCRIPT

我們需要打開用戶的攝影機。 頁面載入時,透過重寫Index.razorOnInitializedAsync()方法來實現此功能。 呼叫你之前寫的 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
$vbLabelText   $csharpLabel

現在新增用於運行網路攝影機視訊串流的HTML標籤:

<section class="section">
    <video autoplay id="video" width="320"></video>
</section>
<section class="section">
    <video autoplay id="video" width="320"></video>
</section>
HTML

拍攝影像

為了從網路攝影機視訊串流中捕獲一幀,讓我們在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);
}
JAVASCRIPT

此函數將擷取一幀,將其編碼為 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(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
$vbLabelText   $csharpLabel

它負責將 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
$vbLabelText   $csharpLabel

IronBarcode 擷取擷取的影像

將 IronBarcode NuGet 套件新增至伺服器專案:

dotnet add package IronBarCode

現在,在伺服器專案中,新增一個 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);
            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
$vbLabelText   $csharpLabel

您可以在這裡找到範例項目。

常見問題解答

如何在 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# 方法可處理影像以進行 BarCode 讀取。

如何在 Blazor 專案中讀取 BarCode?

您可以在伺服器端 API 方法中使用條碼函式庫的讀取器類別,透過解碼 base64 影像字串來讀取條碼,從影像中擷取條碼值。

在 Blazor 中使用條碼函式庫的先決條件是什麼?

確保您已設定 Blazor 伺服器專案、安裝必要的 NuGet 套件,並已設定 JavaScript 以處理網路攝影機的輸入。您還需要有效的 BarCode 函式庫授權金鑰。

如何在 Blazor 中將擷取的影像傳送至伺服器?

透過在 JavaScript 中使用 DotNetObjectReference 以影像資料來呼叫 C# 方法,將擷取的影像傳送至伺服器,此方法會以 base64 影像字串來呼叫。

此 BarCode 程式庫可以處理 QR 碼嗎?

是的,條碼函式庫可以在 .NET 應用程式中建立、讀取和管理條碼與 QR 代碼,包括使用 Blazor 建立的應用程式。

哪裡可以找到使用 BarCode 程式庫的 Blazor 專案範例?

使用 BarCode 程式庫的 Blazor 專案範例可從文章結論部分所提供的連結下載。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。

準備好開始了嗎?
Nuget 下載 1,979,979 | Version: 2025.11 剛發表