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

在 Blazor 中使用 IronBarcode

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

這篇操作指南包含詳細說明,指導您如何在 Blazor 專案中整合 IronBarcode。 舉例來說,我們將在 Blazor 應用程式中使用 IronBarcode,以掃描透過使用者網路攝影機擷取的條碼/QR 碼。

建立 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

我們需要開啟使用者的網路攝影機。 請在頁面載入時,透過覆寫 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
$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

它負責將 getFrame() 中的編碼圖像透過 JavaScript 傳送至伺服器端 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 方法來處理已編碼的圖片,並擷取 BarCode/QR 碼的值。 以下程式碼將 BarCode 讀取功能新增至 Blazor 專案中。 我們會對掃描的圖像進行預處理,並將其傳入 FromStream 方法中。 將 Image 物件傳入 BarcodeReader 類別中的方法,即可在 Blazor 中掃描 BarCode。 生成的 BARCODE 值可透過 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中將捕捉的影像發送到伺服器?

通過在JavaScript中使用DotNetObjectReference調用C#方法,將捕捉的影像資料以及base64影像字串發送到伺服器。

這個條碼程式庫可以處理QR碼嗎?

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

在何處可以找到使用條碼程式庫的Blazor範例專案?

一個使用條碼程式庫的Blazor範例專案可從文章結論部分提供的鏈接下載。

IronBarcode支援批次處理條碼嗎?

是的,IronBarcode支援批次處理,允許開發者在一次操作中生成或讀取多個條碼,提升大規模應用的效率。

Curtis Chau
技術撰稿人

Curtis Chau 擁有卡爾頓大學(Carleton University)的電腦科學學士學位,專精於前端開發,並精通 Node.js、TypeScript、JavaScript 及 React。他熱衷於打造直觀且美觀的用戶介面,喜歡運用現代框架,並創建結構完善、視覺上吸引人的手冊。

除了開發工作之外,Curtis 對物聯網(IoT)抱有濃厚興趣,致力於探索整合硬體與軟體的創新方法。閒暇時,他喜歡玩遊戲和開發 Discord 機器人,將對科技的熱愛與創意相結合。

準備好開始了嗎?
Nuget 下載 2,230,745 | 版本: 2026.5 just released
Still Scrolling Icon

還在捲動嗎?

想要快速證明? PM > Install-Package BarCode
執行範例 看您的字串變成 BarCode。