跳過到頁腳內容
使用 IRONBARCODE

使用功能強大的條碼掃描器庫在 Windows 應用程式中使用 .NET MAUI 掃描條碼

您不需要與複雜的相機驅動程式或無止盡的權限循環搏鬥,就能讓條碼掃描器在 .NET MAUI 中運作。 大多數開發人員一想到"Barcode"就會馬上開始擔心即時攝影機串流的開銷。 還有更好的途徑 透過使用 IronBarcode .NET 函式庫,您可以直接從 JPEG 或 PNG 等影像檔案掃描條碼,完全避免令人頭痛的相機管理問題。 雖然本教學的重點是 Microsoft Windows,但完全相同的程式碼也可以在您的 Android 應用程式和 iOS 專案上執行。

開始使用免費試用版來跟進。

如何為條碼掃描建立 .NET MAUI 應用程式?

在 Visual Studio Code 或 Visual Studio 中設定 .NET MAUI 專案非常簡單直接,本教學中我們將採用 Visual Studio。 啟動 Visual Studio 2022 或更新版本,選擇"建立新專案",然後選取 .NET MAUI App 模板。 輸入您的專案名稱,並選擇您的目標平台,在本教程中,我們著重於 Windows 部署。

IronBarcode 與 Scanbot SDK 等需要在 MauiProgram.cs 中進行複雜初始化的解決方案不同,前者需要進行變數建置配置和攝影機預覽設定,而 IronBarcode 則不需要特別註冊。 公共靜態類 MauiProgram 與預設範本保持不變,使 .NET MAUI 應用程式的整合變得非常簡單。

要安裝 IronBarcode NuGet 套件,您可以使用命令選項板(VS Code 中的 Ctrl+Shift+P)或在 Visual Studio 的套件管理員控制台中執行以下命令:

Install-Package BarCode

此單一 NuGet 套件安裝提供條碼掃瞄、多重條碼掃瞄及 QR 碼辨識所需的一切。 最新版本支援所有主要的 BarCode 格式,不需要額外的相依性,不像基於攝影機的掃描器通常需要權限處理器和 CameraView 控制組態。

若要在生產環境中使用 IronBarcode,您需要申請授權金鑰。 您可以在 MauiProgram.cs 中或 App.xaml.cs 建構器內設定:

IronBarCode.License.LicenseKey = "YOUR_IRONBARCODE_LICENSE_KEY";
IronBarCode.License.LicenseKey = "YOUR_IRONBARCODE_LICENSE_KEY";
Imports IronBarCode

IronBarCode.License.LicenseKey = "YOUR_IRONBARCODE_LICENSE_KEY"
$vbLabelText   $csharpLabel

處理 iOS 和 Android 的權限

使用以圖像為基礎的 .NET 函式庫的主要好處之一是簡化了權限模型。 傳統的相機式掃描器需要在 AndroidManifest.xml 中取得下列權限:

  • <uses-permission android:name="android.permission.CAMERA" />
  • <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

在為 iOS 和 Android 建置時,如果處理不當,這些所需的權限通常會導致"權限拒絕"錯誤。 然而,由於 IronBarcode 可從變數影像或檔案串流進行掃描,因此您只需確保應用程式可存取檔案系統。

哪種介面設計最適合 MAUI 條碼掃描器?

簡潔、實用的介面可讓使用者選擇包含 BarCode 的影像檔案,並檢視掃描結果。 以下 XAML 為您的 .NET MAUI 應用程式建立了一個簡單但有效的 BarCode 掃描器 UI:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="BarcodeScanner.MainPage">
    <ScrollView>
        <VerticalStackLayout Spacing="20" Padding="30">
            <Label Text="MAUI Barcode Scanner"
                   FontSize="24"
                   HorizontalOptions="Center" />
            <Button x:Name="SelectImageBtn"
                    Text="Select Image File"
                    Clicked="OnSelectImage" />
            <Image x:Name="SelectedImageDisplay"
                   HeightRequest="250" />
            <Label x:Name="ResultsLabel"
                   Text="Barcode results will display here" />
        </VerticalStackLayout>
    </ScrollView>
</ContentPage>
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="BarcodeScanner.MainPage">
    <ScrollView>
        <VerticalStackLayout Spacing="20" Padding="30">
            <Label Text="MAUI Barcode Scanner"
                   FontSize="24"
                   HorizontalOptions="Center" />
            <Button x:Name="SelectImageBtn"
                    Text="Select Image File"
                    Clicked="OnSelectImage" />
            <Image x:Name="SelectedImageDisplay"
                   HeightRequest="250" />
            <Label x:Name="ResultsLabel"
                   Text="Barcode results will display here" />
        </VerticalStackLayout>
    </ScrollView>
</ContentPage>
$vbLabelText   $csharpLabel

此版面提供了一個影像檔案選擇按鈕、一個顯示所選影像的區域,以及一個條碼偵測結果的標籤。 本設計適用於所有 .NET MAUI 目標平台,同時在 Windows 上維持原生效能。

如何從影像檔執行 BarCode 檢測?

在您的 MainPage.xaml.cs 中,您可以使用 async void OnAppearing 等生命週期方法來初始化設定或檢查使用者是否已提供必要的檔案存取權限。

公共部分類別 MainPage 包含掃描邏輯。 IronBarcode 的 BarcodeReader.Read 方法處理所有複雜的條碼偵測,支援掃描 JPEG、PNG、GIF、TIFF 和 BMP 格式的條碼。 以下是完整的實作:

using IronBarCode;
namespace BarcodeScanner;
public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }
    private async void OnSelectImage(object sender, EventArgs e)
    {
        try
        {
            // Open file picker for image selection
            var result = await FilePicker.PickAsync(new PickOptions
            {
                FileTypes = FilePickerFileType.Images,
                PickerTitle = "Select a barcode image"
            });
            if (result != null)
            {
                // Display the selected image
                var stream = await result.OpenReadAsync();
                SelectedImageDisplay.Source = ImageSource.FromStream(() => stream);
                // Read barcodes from the image file
                var barcodes = BarcodeReader.Read(result.FullPath);
                // Display all detected barcode values
                if (barcodes.Count > 0)
                {
                    string output = string.Join("\n",
                        barcodes.Select(b => $"{b.BarcodeType}: {b.Value}"));
                    ResultsLabel.Text = output;
                }
                else
                {
                    ResultsLabel.Text = "No barcodes detected in image";
                }
            }
        }
        catch (Exception ex)
        {
            ResultsLabel.Text = $"Error occurred: {ex.Message}";
        }
    }
}
using IronBarCode;
namespace BarcodeScanner;
public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }
    private async void OnSelectImage(object sender, EventArgs e)
    {
        try
        {
            // Open file picker for image selection
            var result = await FilePicker.PickAsync(new PickOptions
            {
                FileTypes = FilePickerFileType.Images,
                PickerTitle = "Select a barcode image"
            });
            if (result != null)
            {
                // Display the selected image
                var stream = await result.OpenReadAsync();
                SelectedImageDisplay.Source = ImageSource.FromStream(() => stream);
                // Read barcodes from the image file
                var barcodes = BarcodeReader.Read(result.FullPath);
                // Display all detected barcode values
                if (barcodes.Count > 0)
                {
                    string output = string.Join("\n",
                        barcodes.Select(b => $"{b.BarcodeType}: {b.Value}"));
                    ResultsLabel.Text = output;
                }
                else
                {
                    ResultsLabel.Text = "No barcodes detected in image";
                }
            }
        }
        catch (Exception ex)
        {
            ResultsLabel.Text = $"Error occurred: {ex.Message}";
        }
    }
}
Imports IronBarCode

Namespace BarcodeScanner
    Public Partial Class MainPage
        Inherits ContentPage

        Public Sub New()
            InitializeComponent()
        End Sub

        Private Async Sub OnSelectImage(sender As Object, e As EventArgs)
            Try
                ' Open file picker for image selection
                Dim result = Await FilePicker.PickAsync(New PickOptions With {
                    .FileTypes = FilePickerFileType.Images,
                    .PickerTitle = "Select a barcode image"
                })
                If result IsNot Nothing Then
                    ' Display the selected image
                    Dim stream = Await result.OpenReadAsync()
                    SelectedImageDisplay.Source = ImageSource.FromStream(Function() stream)
                    ' Read barcodes from the image file
                    Dim barcodes = BarcodeReader.Read(result.FullPath)
                    ' Display all detected barcode values
                    If barcodes.Count > 0 Then
                        Dim output As String = String.Join(vbCrLf, barcodes.Select(Function(b) $"{b.BarcodeType}: {b.Value}"))
                        ResultsLabel.Text = output
                    Else
                        ResultsLabel.Text = "No barcodes detected in image"
                    End If
                End If
            Catch ex As Exception
                ResultsLabel.Text = $"Error occurred: {ex.Message}"
            End Try
        End Sub
    End Class
End Namespace
$vbLabelText   $csharpLabel

輸出

!a href="/static-assets/barcode/blog/net-maui-scan-barcode/net-maui-scan-barcode-1.webp">.NET MAUI 使用強大的條碼掃描器函式庫在 Windows 應用程式中掃描條碼:圖片 1 - 掃描條碼輸出

BarcodeReader.Read 方法會自動偵測並解碼影像檔案中存在的所有條碼格式。每個結果都包含條碼類型、值和位置資訊。 此方法省去了像 Scanbot SDK 這樣基於攝影機的解決方案所需的攝影機權限、Android 和 iOS 特定組態或 BarCode 偵測事件處理。

private async void ProcessResults(BarcodeResults barcodes)
{
    if (barcodes.Count > 0)
    {
        string msg = $"Found {barcodes.Count} barcodes.";
        // Use await DisplayAlert to show results to the user
        await DisplayAlert("Scan Success", msg, "OK");
    }
    else
    {
        await DisplayAlert("No Results", "No barcodes were found in the image.", "OK");
    }
}
private async void ProcessResults(BarcodeResults barcodes)
{
    if (barcodes.Count > 0)
    {
        string msg = $"Found {barcodes.Count} barcodes.";
        // Use await DisplayAlert to show results to the user
        await DisplayAlert("Scan Success", msg, "OK");
    }
    else
    {
        await DisplayAlert("No Results", "No barcodes were found in the image.", "OK");
    }
}
Private Async Sub ProcessResults(barcodes As BarcodeResults)
    If barcodes.Count > 0 Then
        Dim msg As String = $"Found {barcodes.Count} barcodes."
        ' Use Await DisplayAlert to show results to the user
        Await DisplayAlert("Scan Success", msg, "OK")
    Else
        Await DisplayAlert("No Results", "No barcodes were found in the image.", "OK")
    End If
End Sub
$vbLabelText   $csharpLabel

使用 await DisplayAlert 提供使用者回饋。

在行動或桌上型電腦環境中,提供即時的回饋至關重要。 掃描完成後,您可以使用 await DisplayAlert 方法來顯示模態對話框,而不是更新標籤。 這可確保使用者在繼續之前確認結果。

如何掃描多個 BarCode 並配置偵測選項?

當您的影像檔案包含多個條碼時,IronBarcode 會自動偵測所有條碼。 當您知道預期的 BarCode 類型時,若要獲得最佳化的效能,請使用 BarcodeReaderOptions:

using IronBarCode;
// Configure options for scanning multiple barcodes
var options = new BarcodeReaderOptions
{
    ExpectMultipleBarcodes = true,
    ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.Code128,
    Speed = ReadingSpeed.Balanced
};
var barcodes = BarcodeReader.Read(imagePath, options);
// Process each detected barcode
foreach (var barcode in barcodes)
{
    Console.WriteLine($"Found: {barcode.Value}");
}
using IronBarCode;
// Configure options for scanning multiple barcodes
var options = new BarcodeReaderOptions
{
    ExpectMultipleBarcodes = true,
    ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.Code128,
    Speed = ReadingSpeed.Balanced
};
var barcodes = BarcodeReader.Read(imagePath, options);
// Process each detected barcode
foreach (var barcode in barcodes)
{
    Console.WriteLine($"Found: {barcode.Value}");
}
Imports IronBarCode

' Configure options for scanning multiple barcodes
Dim options As New BarcodeReaderOptions With {
    .ExpectMultipleBarcodes = True,
    .ExpectBarcodeTypes = BarcodeEncoding.QRCode Or BarcodeEncoding.Code128,
    .Speed = ReadingSpeed.Balanced
}
Dim barcodes = BarcodeReader.Read(imagePath, options)

' Process each detected barcode
For Each barcode In barcodes
    Console.WriteLine($"Found: {barcode.Value}")
Next
$vbLabelText   $csharpLabel

多條條碼掃描輸出

!a href="/static-assets/barcode/blog/net-maui-scan-barcode/net-maui-scan-barcode-2.webp">.NET MAUI 使用強大的條碼掃描器函式庫在 Windows 應用程式中掃描條碼:圖片 2 - 掃描多個 BarCode 的輸出。

指定 ExpectBarcodeTypes 可集中偵測相關格式,從而提高掃描速度。 速度屬性可平衡精確度與效能; 使用 ReadingSpeed.Faster 掃描原始影像,或使用 ReadingSpeed.Detailed 掃描具有旋轉或雜訊的高難度掃描。

這種靈活性使得 .NET MAUI 條碼掃描器適用於各種不同的情境:讀取產品編碼的零售應用程式、處理運送標籤的倉儲系統,或是擷取內嵌 QR 代碼的文件工作流程。

為何選擇影像式條碼掃描?

基於影像的條碼掃描為 .NET MAUI 掃描條碼開發提供了明顯的優勢。 Scanbot SDK 和類似的工具著重於即時攝影機預覽功能,而 IronBarcode 的方法則提供更直接的整合、跨平台的一致行為,以及處理來自任何來源的現有影像檔案的能力,包括掃描文件、電子郵件附件或使用者上傳的檔案。

對於 Android 和 iOS 部署,相同的程式碼無需修改即可運作,不需要相機權限或特定平台的設定。

進階功能:AR 覆疊 vs. 影像處理。

有些 SDK 著重於即時 AR 疊層 (Augmented Reality) 以突顯攝影機畫面中的條碼,而 IronBarcode 則專注於靜態影像的高速精準度。 這是跨平台應用程式的理想選擇,在這些應用程式中,使用者可能會上傳收據、運送標籤或螢幕截圖,而非在現場"即時"掃描物品。

透過消除對即時攝影機饋送的需求,您可以減少電池消耗,並避免行動 AR 元件常有的 UI 閃爍問題。

結論

使用 IronBarcode 建立 .NET MAUI 條碼掃描器只需最少的程式碼,同時提供強大的條碼偵測功能。 以影像檔案為基礎的方式,省去了相機權限、特定裝置的設定以及複雜的初始化,簡化了開發過程。 您專注於應用程式邏輯,而 IronBarcode 則處理掃描工作。

完整的 API 文件涵蓋其他功能,包括 PDF 條碼讀取、批次處理和進階影像篩選器。 準備好在您的跨平台 .NET MAUI 專案中實作條碼掃描嗎? 購買授權以供生產使用,或透過免費試用探索完整的功能集。

!{--01001100010010010100001001010010010000010101001001011001010111110100011101000101010101 01000101111101010011010101000100000101010010010101000100010101000100010111110101011101001000110 1010101000100100001011111010100000101001001001111010001000101010101010000110101010100101010101011 10101010001010010010010010010000010100110001011111010000100100110001001111101000011010010111111010000110100101110--

常見問題解答

如何在.NET MAUI中建立條碼掃描器?

您可以使用 IronBarcode .NET 庫在 .NET MAUI 中建立條碼掃描器,該程式庫可讓您直接從 JPEG 或 PNG 等影像檔案掃描條碼。這種方法避免了管理即時攝影機串流的複雜性。

我可以在安卓和iOS系統上使用IronBarcode進行條碼掃描嗎?

是的,您可以在 Android 和 iOS 專案中使用相同的 IronBarcode 條碼掃描代碼。該庫兼容這些平台,可實現無縫整合。

在 .NET MAUI 應用程式中使用 IronBarcode 有哪些好處?

在 .NET MAUI 應用程式中使用 IronBarcode 可以簡化條碼掃描,無需處理複雜的攝影機驅動程式或權限。它允許直接從影像檔案進行掃描,使掃描過程更輕鬆、更有效率。

在.NET MAUI中管理用於條碼掃描的攝影機視訊串流是否困難?

由於相機驅動程式和權限循環的問題,在 .NET MAUI 中管理用於條碼掃描的相機流可能非常複雜。但是,使用 IronBarcode,您可以透過掃描影像檔案中的條碼來避免這些挑戰。

IronBarcode是否支援掃描二維碼以及條碼?

是的,IronBarcode 支援掃描條碼和二維碼,為您的應用程式提供多種類型的程式碼掃描需求解決方案。

IronBarcode僅限於Windows應用程式?

不,雖然本教學專注於 Microsoft Windows,但 IronBarcode 也相容於 Android 和 iOS,使其成為跨平台開發的靈活選擇。

IronBarcode支援哪些影像檔案格式進行掃描?

IronBarcode 支援掃描多種影像檔案格式,包括 JPEG 和 PNG,這使得條碼掃描的應用場景更加廣泛。

Curtis Chau
技術撰稿人

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

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