如何在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.razor 的方法來執行此操作。 呼叫你之前寫的JavaScript函數 initializeCamera()

protected override async Task OnInitializedAsync()
{
    await JSRuntime.InvokeVoidAsync("initializeCamera");
}
protected override async Task OnInitializedAsync()
{
    await JSRuntime.InvokeVoidAsync("initializeCamera");
}
$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();
    }
}
$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));
}
$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; }
}
$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 機器人,結合科技與創意的樂趣。

準備好開始了嗎?
Nuget 下載 2,108,094 | 版本: 2026.3 剛剛發布
Still Scrolling Icon

還在捲動嗎?

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