如何在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 文件來啟用網路攝影機支持。該文件應包含訪問和流式傳輸網路攝影機視頻的函數,可以通過 Blazor 使用 JS 互操作調用。

需要哪些 JavaScript 才能訪問網路攝影機?

JavaScript 應包括像 initializeCamera() 這樣的函數,它使用 navigator.mediaDevices.getUserMedia 請求攝影機訪問並將視頻流傳送到 HTML 視頻元素。

如何在 Blazor 中捕獲和處理來自網路攝影機的畫面?

編寫一個 JavaScript 函數來捕獲當前視頻畫面,將其轉換為 base64 編碼圖像,並使用 Blazor 的 JS 互操作將其發送到 C# 方法。然後,C# 方法可以對圖像進行處理以進行條碼讀取。

我如何在 Blazor 專案中讀取條碼?

您可以通過解碼伺服器端 API 方法中的 base64 圖像字串,使用條碼庫的讀取器類提取圖像中的條碼值來讀取條碼。

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

確保您已設置 Blazor 伺服器專案,安裝所需的 NuGet 套件,並配置 JavaScript 以處理網路攝影機輸入。此外,您還需要該條碼庫的有效許可密鑰。

如何將捕獲的圖像發送到 Blazor 中的伺服器?

通過使用 DotNetObjectReference 在 JavaScript 中調用 C# 方法,將捕獲的圖像數據以及 base64 圖像字串發送給伺服器端。

此條碼庫可以處理 QR 碼嗎?

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

我在哪裡可以找到使用條碼庫的 Blazor 專案範例?

在文章結論部分提供的鏈接中可以下載使用條碼庫的 Blazor 專案範例。

Curtis Chau
技術撰稿人

Curtis Chau 擁有電腦科學學士學位(卡爾頓大學),專長於前端開發,精通 Node.js、TypeScript、JavaScript 和 React。Curtis 對製作直覺且美觀的使用者介面充滿熱情,他喜歡使用現代化的架構,並製作結構良好且視覺上吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 也有濃厚的興趣,他喜歡探索整合硬體與軟體的創新方式。在空閒時間,他喜歡玩遊戲和建立 Discord bots,將他對技術的熱愛與創意結合。

準備好開始了嗎?
Nuget 下載 2,070,733 | 版本: 2026.2 剛剛發布