跳至頁尾內容
使用IRONBARCODE

如何在C#中構建.NET MAUI條碼掃描器?

IronBarcode 讓您可以直接從.NET MAUI應用程式內的影像檔案掃描條碼——無需相機流,無需驅動程式配置,無需平台特定的許可迴圈。

您可以透過單一方法呼叫從JPEG、PNG、GIF、TIFF和BMP檔案中掃描條碼。 相同的程式碼在Windows、Android和iOS上運行無需修改。 開始使用免費試用,以便按照下面的程式碼範例進行操作。

如何建立用於條碼掃描的.NET MAUI專案?

在Visual Studio中設定.NET MAUI專案非常簡單。 啟動Visual Studio 2022或更高版本,選擇建立新專案,選擇.NET MAUI 應用範本,輸入您的專案名稱,然後選擇目標平台。 本教程著重於Windows專案部署,雖然相同的專案也在Android和iOS上運行。 .NET MAUI 是Microsoft用來從單一共享程式碼庫中使用C#和XAML構建原生行動和桌面應用的平台框架。

與需要MauiProgram.cs註冊的相機解決方案(例如ZXing.Net.MAUI)不同,IronBarcode 不需要特殊配置。 您的MauiProgram.cs保持在預設範本狀態。 這樣可以使您的啟動程式碼免於第三方處理程式註冊,並減少啟動時出現初始化錯誤的範圍。

要安裝IronBarcode,請在套件管理控制台中運行此命令:

Install-Package BarCode

此單一套件為您提供條碼掃描、QR碼識別、多人條碼檢測和條碼生成功能。 不需要額外的依賴項。

要在生產中啟用IronBarcode,請在MauiProgram.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

您可以從IronBarcode 授權頁獲得金鑰,或者從免費試用授權開始。

圖像基礎掃描的許可有何不同?

傳統基於相機的條碼掃描器需要在平台清單中顯式許可。 在Android中,您需要新增到AndroidManifest.xml

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

在iOS中,您需要在NSCameraUsageDescription。 在運行時處理被拒絕的許可導致容易被忽視的錯誤路徑。

因為IronBarcode是從文件流而不是相機預覽讀取的,您只需要文件系統的存取權。 在Windows上,這是自動授予的。 在Android和iOS上,FilePicker會在使用者選擇圖像時處理使用者同意——不需要手動要求授權。

哪種XAML接口最適合MAUI條碼掃描器?

一個最小的接口——一個影像選擇按鈕、一個影像顯示區域和一個結果標籤——覆蓋了大多數條碼掃描場景。 下面的XAML為.NET MAUI 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 appear 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 appear here" />
        </VerticalStackLayout>
    </ScrollView>
</ContentPage>
XML

該佈局提供了一個按鈕來觸發文件選擇器,一個影像顯示區域,以及一個用於解碼條碼值的標籤。 它在所有.NET MAUI目標平台上正確呈現,無需平台特定的調整。

對於生產應用,建議將CollectionView以在可滾動列表中顯示多個條碼結果,特別是在掃描包含多個條碼的文件時。

如何在.NET MAUI中從影像文件掃描條碼?

MainPage.xaml.cs中的後置程式碼處理影像選擇和條碼讀取。 BarcodeResults集合。 集合中的每個項目都公開條碼BarcodeType和位置座標。

以下是完整的實現:

using IronBarCode;
namespace BarcodeScanner;

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }

    private async void OnSelectImage(object sender, EventArgs e)
    {
        try
        {
            // Open the system file picker filtered to image types
            var result = await FilePicker.PickAsync(new PickOptions
            {
                FileTypes = FilePickerFileType.Images,
                PickerTitle = "Select a barcode image"
            });

            if (result != null)
            {
                // Display the selected image in the UI
                var stream = await result.OpenReadAsync();
                SelectedImageDisplay.Source = ImageSource.FromStream(() => stream);

                // Decode all barcodes found in the image
                var barcodes = BarcodeReader.Read(result.FullPath);

                if (barcodes.Count > 0)
                {
                    // Build a display string listing each barcode type and value
                    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: {ex.Message}";
        }
    }
}
using IronBarCode;
namespace BarcodeScanner;

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }

    private async void OnSelectImage(object sender, EventArgs e)
    {
        try
        {
            // Open the system file picker filtered to image types
            var result = await FilePicker.PickAsync(new PickOptions
            {
                FileTypes = FilePickerFileType.Images,
                PickerTitle = "Select a barcode image"
            });

            if (result != null)
            {
                // Display the selected image in the UI
                var stream = await result.OpenReadAsync();
                SelectedImageDisplay.Source = ImageSource.FromStream(() => stream);

                // Decode all barcodes found in the image
                var barcodes = BarcodeReader.Read(result.FullPath);

                if (barcodes.Count > 0)
                {
                    // Build a display string listing each barcode type and value
                    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: {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 the system file picker filtered to image types
                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 in the UI
                    Dim stream = Await result.OpenReadAsync()
                    SelectedImageDisplay.Source = ImageSource.FromStream(Function() stream)

                    ' Decode all barcodes found in the image
                    Dim barcodes = BarcodeReader.Read(result.FullPath)

                    If barcodes.Count > 0 Then
                        ' Build a display string listing each barcode type and value
                        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: {ex.Message}"
            End Try
        End Sub
    End Class

End Namespace
$vbLabelText   $csharpLabel

BarcodeReader.Read處理給定路徑上的文件,自動檢測所有存在的條碼符號學,並立即返回結果。 該方法支持所有主要的1D和2D條碼格式,包括Code 128、Code 39、QR碼、Data Matrix、PDF417和EAN-13。

FilePicker.PickAsync呼叫將選擇器限制為影像型別,因此使用者不能意外選擇非影像文件。 如果if (result != null)防護將靜默處理該情況。

如何在對話框中顯示掃描結果?

對於簡短的確認資訊,DisplayAlert 提供了一個模態對話框而無需額外的UI元素:

private async void ShowScanSummary(BarcodeResults barcodes)
{
    if (barcodes.Count > 0)
    {
        // Inform the user how many barcodes were detected
        string message = $"Found {barcodes.Count} barcode(s) in the image.";
        await DisplayAlert("Scan Complete", message, "OK");
    }
    else
    {
        await DisplayAlert("No Results", "No barcodes were found in the image.", "OK");
    }
}
private async void ShowScanSummary(BarcodeResults barcodes)
{
    if (barcodes.Count > 0)
    {
        // Inform the user how many barcodes were detected
        string message = $"Found {barcodes.Count} barcode(s) in the image.";
        await DisplayAlert("Scan Complete", message, "OK");
    }
    else
    {
        await DisplayAlert("No Results", "No barcodes were found in the image.", "OK");
    }
}
Private Async Sub ShowScanSummary(barcodes As BarcodeResults)
    If barcodes.Count > 0 Then
        ' Inform the user how many barcodes were detected
        Dim message As String = $"Found {barcodes.Count} barcode(s) in the image."
        Await DisplayAlert("Scan Complete", message, "OK")
    Else
        Await DisplayAlert("No Results", "No barcodes were found in the image.", "OK")
    End If
End Sub
$vbLabelText   $csharpLabel

這種模式很適合簡單的確認流程。 對於需要根據解碼值執行操作的應用程式——例如,通過其條碼在條碼庫存管理系統中查找產品——將OnSelectImage處理程式傳遞給您的業務邏輯層。

如何掃描多個條碼和調整檢測速度?

當影像包含多個條碼時,IronBarcode預設會檢測它們。 當您知道預期的格式時,為了更好的性能,可以在呼叫BarcodeReaderOptions

using IronBarCode;

// Target only QR codes and Code 128 for faster detection
var options = new BarcodeReaderOptions
{
    ExpectMultipleBarcodes = true,
    ExpectBarcodeTypes     = BarcodeEncoding.QRCode | BarcodeEncoding.Code128,
    Speed                  = ReadingSpeed.Balanced
};

var barcodes = BarcodeReader.Read(imagePath, options);

foreach (var barcode in barcodes)
{
    Console.WriteLine($"Type: {barcode.BarcodeType} | Value: {barcode.Value}");
}
using IronBarCode;

// Target only QR codes and Code 128 for faster detection
var options = new BarcodeReaderOptions
{
    ExpectMultipleBarcodes = true,
    ExpectBarcodeTypes     = BarcodeEncoding.QRCode | BarcodeEncoding.Code128,
    Speed                  = ReadingSpeed.Balanced
};

var barcodes = BarcodeReader.Read(imagePath, options);

foreach (var barcode in barcodes)
{
    Console.WriteLine($"Type: {barcode.BarcodeType} | Value: {barcode.Value}");
}
Imports IronBarCode

' Target only QR codes and Code 128 for faster detection
Dim options As New BarcodeReaderOptions With {
    .ExpectMultipleBarcodes = True,
    .ExpectBarcodeTypes = BarcodeEncoding.QRCode Or BarcodeEncoding.Code128,
    .Speed = ReadingSpeed.Balanced
}

Dim barcodes = BarcodeReader.Read(imagePath, options)

For Each barcode In barcodes
    Console.WriteLine($"Type: {barcode.BarcodeType} | Value: {barcode.Value}")
Next
$vbLabelText   $csharpLabel

ExpectBarcodeTypes屬性將檢測引擎範圍縮小到指定的符號學。 將ReadingSpeed.Faster適合高對比度、無畸變的影像。 ReadingSpeed.Detailed應用額外的影像校正處理並處理旋轉、傾斜和低解析度輸入,但額外增加處理時間。

ExpectMultipleBarcodes = true告訴讀取器在第一次匹配後繼續掃描,而不是提前返回。 在單條碼場景中,省略此選項可從每次掃描中節省幾毫秒。

這種配置使得掃描器能夠適用於各種應用程式:零售應用來閱讀產品條碼、倉庫工具來處理運送照片上的列印條碼標籤,或文件工作流程從上傳的發票中提取QR碼。

如何處理具有挑戰性或低品質的影像?

生產影像很少是完美無缺的。倉庫照片在惡劣照明下拍攝,來自電子郵件客戶端的螢幕截圖以及掃描文件都會引入噪點、壓縮失真和幾何形變。 IronBarcode提供ImageFilterCollection來預處理圖像,以便進行解碼:

using IronBarCode;
using IronSoftware.Drawing;

// Apply corrections for a low-quality warehouse photo
var options = new BarcodeReaderOptions
{
    ImageFilters = new ImageFilterCollection
    {
        new SharpenFilter(),
        new ContrastFilter(1.2f),
        new DenoiseFilter()
    },
    Speed = ReadingSpeed.Detailed
};

var barcodes = BarcodeReader.Read(imagePath, options);
using IronBarCode;
using IronSoftware.Drawing;

// Apply corrections for a low-quality warehouse photo
var options = new BarcodeReaderOptions
{
    ImageFilters = new ImageFilterCollection
    {
        new SharpenFilter(),
        new ContrastFilter(1.2f),
        new DenoiseFilter()
    },
    Speed = ReadingSpeed.Detailed
};

var barcodes = BarcodeReader.Read(imagePath, options);
Imports IronBarCode
Imports IronSoftware.Drawing

' Apply corrections for a low-quality warehouse photo
Dim options As New BarcodeReaderOptions With {
    .ImageFilters = New ImageFilterCollection From {
        New SharpenFilter(),
        New ContrastFilter(1.2F),
        New DenoiseFilter()
    },
    .Speed = ReadingSpeed.Detailed
}

Dim barcodes = BarcodeReader.Read(imagePath, options)
$vbLabelText   $csharpLabel

SharpenFilter從壓縮或失焦圖像中恢復邊緣定義。 ContrastFilter有助於當光線不均勻時。 DenoiseFilter減少低解析度掃描中的斑點。 將這些過濾器與ReadingSpeed.Detailed結合使用可最大化難以讀取材料的讀取率。

對於接受來自多種來源的使用者上載圖像的.NET MAUI應用,預設應用保守的過濾器集,並在第二次重試時升級為更強烈的校正,不會在常見情況下增加明顯的延遲,從而改善使用者體驗。 您還可以直接將BarcodeReader.Read,當圖像來自網路響應而不是文件系統時,這很有用。 有關其他輸入源範例,請參見IronBarcode 使用指南

為什麼影像基礎掃描適合.NET MAUI應用程式?

通過CameraView控制進行實時相機掃描需要平台特定的許可授予、相機預覽的生命週期管理以及焦點事件的處理。 在iOS上,這還意味著需要配置AVCaptureSession; 在Android上,配置為CameraX。 每個平台都有其自身的故障模式。

影像基礎掃描消除了該整體型別的問題。 IronBarcode API參考顯示byte[]——任何您MAUI應用可以產生的表現形式。 這意味著相同的掃描邏輯無論影像來自FilePicker、網路下載、渲染成位圖的PDF頁面,還是電子郵件附件都可以運行。

電池消耗更低,因為鏡頭硬體保持關閉。 UI不會因為即時預覽而閃爍,也不需要跨應用程式暫停和恢復管理相機生命週期事件。 在平板和桌面形狀上——即時相機觀景器很少合適——影像基礎解碼是自然的預設選擇,而不是折衷選擇。使用者可以使用相同的FilePicker呼叫,無論裝置型別如何都可以從雲端儲存、本地文件夾或相機相冊中打開檔案。

對於使用者拍攝條碼標籤並上傳的工作流——在ASP.NET條碼掃描器網路應用中很常見——相同的BarcodeReader.Read呼叫在移動客戶端和伺服器上都能運行,消除了需要維護兩個掃描實施的需求。

IronBarcode 如何與 ZXing.Net.MAUI 比較?

ZXing.Net.MAUI 針對即時相機掃描進行目標化,當實時觀景器反饋是產品需求時運行良好。 它需要CameraView整合、平台處理器註冊和運行時許可請求。

IronBarcode針對基於文件和流的解碼,涵蓋了大多數企業文件工作流。 它支持更廣泛的符號學範圍,包括PDF417Data MatrixCode 128,並提供ZXing未曝光的影像過濾器預處理。 對於使用者捕捉或上傳圖像而不是即時掃描項目的應用程式,IronBarcode 更符合直接匹配。

如果您的應用需要即時相機掃描和基於文件的解碼,您可以結合這兩個庫:ZXing.Net.MAUI 用於觀景器工作流程,IronBarcode 用於批處理文件處理。

您的下一步是什麼?

用IronBarcode構建.NET MAUI條碼掃描器不超過30行C#程式碼。 影像文件方法使您的MAUI程式碼庫免於相機許可邏輯和平台特定的初始化,並且相同的掃描呼叫在Windows、Android和iOS上相同運行。

IronBarcode API文件涵蓋其他功能:從PDF文件中閱讀條碼、批處理多個圖像、編寫自定義影像過濾器和在閱讀條碼的同時產生條碼。 功能概述列出了所有支持的符號學和格式。

開始免費試用來在您的專案中測試IronBarcode,或在準備生產部署時購買授權

現在開始使用IronBarcode。
green arrow pointer

常見問題

如何在 .NET MAUI 中建立不需要相機的條形碼掃描器?

通過 NuGet (`Install-Package BarCode`) 安裝 IronBarcode,然後使用 `FilePicker.PickAsync` 獲得的路徑調用 `BarcodeReader.Read(filePath)`。不需要相機權限或 `CameraView` 設置。

IronBarcode 可以在 .NET MAUI 中掃描 Android 和 iOS 上的條形碼嗎?

可以。相同的 `BarcodeReader.Read` 調用可在 Windows、Android 和 iOS 上運行,無需任何特定平台的程式碼路徑或清單更改。

IronBarcode 支持哪些圖像格式的條形碼掃描?

IronBarcode 可以從 JPEG、PNG、GIF、TIFF 和 BMP 文件讀取條形碼。它還接受 `Stream`、`Bitmap` 和 `byte[]` 輸入,因此網路響應的圖像無需先寫入磁碟即可運行。

如何在 .NET MAUI 中從單個圖像掃描多個條形碼?

在 `BarcodeReaderOptions` 中設置 `ExpectMultipleBarcodes = true`,並將選項傳遞給 `BarcodeReader.Read`。閱讀器會在單個 `BarcodeResults` 集合中返回所有檢測到的條形碼。

IronBarcode 和 ZXing.Net.MAUI 有什麼區別?

ZXing.Net.MAUI 針對透過 `CameraView` 控制進行即時相機掃描。IronBarcode 針對基於文件和流的解碼,支持更多的符號(包括 PDF417 和資料矩陣),並為低質量輸入提供圖像過濾預處理。

如何改進對模糊或低質量圖像的條形碼檢測?

在 `BarcodeReaderOptions` 中新增 `ImageFilterCollection`,並使用 `SharpenFilter`、`ContrastFilter` 和 `DenoiseFilter`,設置 `Speed = ReadingSpeed.Detailed`。這會在解碼階段前應用圖像校正。

IronBarcode 支持在 .NET MAUI 中哪些條形碼格式?

IronBarcode 支持所有主要的 1D 和 2D 符號:Code 128、Code 39、QR 碼、資料矩陣、PDF417、EAN-13、EAN-8、UPC-A、UPC-E、Aztec 等。完整列表在 IronBarcode 功能頁面上。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話