如何在 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");
}
$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 檔案來啟用攝影機支援。該檔案應包含用於存取和傳輸攝影機視訊的函數,這些函數可以透過 JS 互通從 Blazor 中呼叫。

存取網路攝影機需要哪些 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 影像字串呼叫該方法。

這個條碼庫可以處理二維碼嗎?

是的,條碼庫可以在 .NET 應用程式(包括使用 Blazor 建置的應用程式)中建立、讀取和管理條碼和二維碼。

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

文章結論部分提供的連結提供了一個使用條碼庫的 Blazor 專案範例供下載。

柯蒂斯·週
技術撰稿人

Curtis Chau擁有卡爾頓大學電腦科學學士學位,專長於前端開發,精通Node.js、TypeScript、JavaScript和React。他熱衷於打造直覺美觀的使用者介面,喜歡使用現代框架,並擅長撰寫結構清晰、視覺效果出色的使用者手冊。

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

準備好開始了嗎?
Nuget 下載 2,035,202 | 版本: 2025.12 剛剛發布