跳過到頁腳內容
使用IRONBARCODE

如何構建.NET MAUI條碼掃描器SDK應用程式

.NET MAUI 提供了一個單一代碼庫的承諾,可針對 Android、iOS 和 Windows。 當您需要整合像條碼掃描這樣的原生硬體特徵時,挑戰就來了。 手動橋接相機 API 意味著需要平台特定的配置、條件編譯指令和幾小時的除錯。 有一個更快的方法。

本教程將向您展示如何在 .NET MAUI 中使用 IronBarcode 建立一個可運行的跨平台條碼掃描器。 您將設置項目、配置平台權限、從影像文件掃描條碼、從 PDF 文檔中讀取條碼,並通過掃描選項處理多種符號——所有這些代碼都可以在任何支持目標上運行。

開始您的免費試用並按照以下步驟進行。

NuGet 用 NuGet 安裝

PM >  Install-Package BarCode

NuGet 查看 https://www.nuget.org/packages/BarCode 以快速安裝。超過 1000 萬次下載,它正在用 C# 改變 PDF 開發。 您還可以下載 DLL

如何在 .NET MAUI 中設置一個條碼掃描器 SDK?

設置一個 .NET MAUI 條碼掃描器 SDK 需要創建一個新項目、安裝 NuGet 套件並配置平台權限。 整個配置過程在 Visual Studio 中只需幾分鐘。

創建 .NET MAUI 項目

打開 Visual Studio 並創建一個新的 .NET MAUI 應用項目。 將項目命名為一些描述性的名稱,如 "BarcodeScanner",並選擇 .NET 8 或更高版本作為目標框架。 Visual Studio 生成具有平台特定文件夾結構的默認項目,用於 Android 和 iOS。

如果您目標 .NET 10,則適用相同的項目模板。 在您的 .csproj 文件中更新 <TargetFrameworks> 屬性,包括必要的 net10.0-iosnet10.0-windows10.0.19041.0。 請參考 .NET MAUI 支持平台文件 以獲取完整的目標框架標識符和最低操作系統版本要求列表。

安裝 IronBarcode

使用套件管理器控制台安裝 IronBarcode NuGet 套件

Install-Package BarCode

此命令會下載並安裝條碼掃描器 SDK 及所需的所有依賴項,以供 .NET MAUI 應用程序使用。

配置平台權限

即使是從圖像文件而不是實時攝像頭流進行掃描,為 .NET MAUI 條碼掃描應用配置以下權限也是個好習慣。

對於 Android,在 Platforms/Android/AndroidManifest.xml 中添加以下內容:

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

對於 iOS,將這些條目添加到 Platforms/iOS/Info.plist 中:

<key>NSPhotoLibraryUsageDescription</key>
<string>Access needed to select barcode images for scanning.</string>
<key>NSCameraUsageDescription</key>
<string>Camera permission for barcode scanning.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Access needed to select barcode images for scanning.</string>
<key>NSCameraUsageDescription</key>
<string>Camera permission for barcode scanning.</string>
XML

初始化 SDK

及早在應用程式生命周期中設置您的授權金鑰,以確保在進行任何掃描調用之前 IronBarcode 已完全激活。 將激活放置在 MauiProgram.cs 中:

using IronBarCode;

var builder = MauiApp.CreateBuilder();
builder
    .UseMauiApp<App>()
    .ConfigureFonts(fonts =>
    {
        fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
    });

// Activate IronBarcode before the app starts
License.LicenseKey = "YOUR_LICENSE_KEY_HERE";

return builder.Build();
using IronBarCode;

var builder = MauiApp.CreateBuilder();
builder
    .UseMauiApp<App>()
    .ConfigureFonts(fonts =>
    {
        fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
    });

// Activate IronBarcode before the app starts
License.LicenseKey = "YOUR_LICENSE_KEY_HERE";

return builder.Build();
$vbLabelText   $csharpLabel

IronBarcode 提供了一個免費試用授權,用於開發和測試。 在啟動時設置一次金鑰;在同一個過程中的所有後續調用 BarcodeReaderBarcodeWriter 都使用已激活的授權。

如何從圖像文件中讀取條碼?

任何 MAUI 條碼掃描器的核心功能都是從選定的圖像中讀取條碼。 BarcodeReader.Read() 方法接受一個文件路徑並返回一個 BarcodeResult 對象集合,每個探測到的條碼一個。

設計用戶界面

MainPage.xaml 中創建一個便捷界面,允許用戶選擇圖像文件並查看掃描的條碼數據:

<?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">
    <VerticalStackLayout Padding="20" Spacing="15">
        <Label Text=".NET MAUI Barcode Scanner" FontSize="24" HorizontalOptions="Center"/>
        <Button Text="Select Image to Scan" Clicked="OnSelectImageClicked"/>
        <Image x:Name="SelectedImageView" HeightRequest="200"/>
        <Label x:Name="ResultLabel" FontSize="16"/>
    </VerticalStackLayout>
</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">
    <VerticalStackLayout Padding="20" Spacing="15">
        <Label Text=".NET MAUI Barcode Scanner" FontSize="24" HorizontalOptions="Center"/>
        <Button Text="Select Image to Scan" Clicked="OnSelectImageClicked"/>
        <Image x:Name="SelectedImageView" HeightRequest="200"/>
        <Label x:Name="ResultLabel" FontSize="16"/>
    </VerticalStackLayout>
</ContentPage>
XML

實現條碼掃描功能

將掃描邏輯添加到 MainPage.xaml.cs 中。 此代碼通過 MAUI FilePicker API 處理圖像選擇,並將所選文件路徑傳遞給 IronBarcode。

using IronBarCode;

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

    private async void OnSelectImageClicked(object sender, EventArgs e)
    {
        var result = await FilePicker.PickAsync(new PickOptions
        {
            FileTypes = FilePickerFileType.Images,
            PickerTitle = "Select a barcode image"
        });

        if (result != null)
        {
            // Display the selected image
            SelectedImageView.Source = ImageSource.FromFile(result.FullPath);

            // Read barcodes from the image file
            var barcodes = BarcodeReader.Read(result.FullPath);

            ResultLabel.Text = barcodes.Any()
                ? $"Found: {barcodes.First().Value}"
                : "No barcodes detected in selected image.";
        }
    }
}
using IronBarCode;

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

    private async void OnSelectImageClicked(object sender, EventArgs e)
    {
        var result = await FilePicker.PickAsync(new PickOptions
        {
            FileTypes = FilePickerFileType.Images,
            PickerTitle = "Select a barcode image"
        });

        if (result != null)
        {
            // Display the selected image
            SelectedImageView.Source = ImageSource.FromFile(result.FullPath);

            // Read barcodes from the image file
            var barcodes = BarcodeReader.Read(result.FullPath);

            ResultLabel.Text = barcodes.Any()
                ? $"Found: {barcodes.First().Value}"
                : "No barcodes detected in selected image.";
        }
    }
}
$vbLabelText   $csharpLabel

輸出

.NET MAUI Barcode Scanner SDK: 在幾分鐘內建構一個跨平台的掃描器:圖 1 - 掃描條碼輸出

BarcodeReader.Read() 方法分析選定的圖像並返回所有檢測到的條碼。 IronBarcode 可以自動識別多種條碼符號,包括 QR 代碼、Code 128、Code 39、EAN-13 和其他许多支持的格式。 結果集合提供像 PageNumber 和每個檢測到的代碼的邊界框坐標等屬性。

如何從 PDF 文件中掃描條碼?

將條碼直接從 PDF 文件中讀取是區分 IronBarcode 與眾多替代方案的一個功能。 這是處理文檔工作流的 .NET MAUI 應用所必須的——運送清單、採購訂單、醫療記錄和類似的平台都依賴於 PDF 內嵌條碼。

BarcodeReader.ReadPdf() 方法接受文件路徑並返回圖像讀取器的相同 BarcodeResult 集合,並帶有附加的 PageNumber 屬性,識別條碼來自哪個 PDF 頁面:

using IronBarCode;

private async void OnSelectPdfClicked(object sender, EventArgs e)
{
    var result = await FilePicker.PickAsync(new PickOptions
    {
        PickerTitle = "Select a PDF with barcodes"
    });

    if (result != null)
    {
        // Read barcodes from every page of the PDF
        var barcodes = BarcodeReader.ReadPdf(result.FullPath);

        var output = string.Join("\n", barcodes.Select(b =>
            $"Page {b.PageNumber}: [{b.BarcodeType}] {b.Value}"));

        await DisplayAlert("Scan Results", output.Length > 0 ? output : "No barcodes found.", "OK");
    }
}
using IronBarCode;

private async void OnSelectPdfClicked(object sender, EventArgs e)
{
    var result = await FilePicker.PickAsync(new PickOptions
    {
        PickerTitle = "Select a PDF with barcodes"
    });

    if (result != null)
    {
        // Read barcodes from every page of the PDF
        var barcodes = BarcodeReader.ReadPdf(result.FullPath);

        var output = string.Join("\n", barcodes.Select(b =>
            $"Page {b.PageNumber}: [{b.BarcodeType}] {b.Value}"));

        await DisplayAlert("Scan Results", output.Length > 0 ? output : "No barcodes found.", "OK");
    }
}
$vbLabelText   $csharpLabel

輸出

.NET MAUI Barcode Scanner SDK: 在幾分鐘內建構一個跨平台的掃描器:圖 2 - 包含 QR 代碼的 PDF 扫描输出

ReadPdf() 方法掃描 PDF 的所有頁面並返回條碼數據及頁碼,這使得處理包含多個條碼的文檔變得簡單。 如果 PDF 跨越幾十頁,考慮傳遞一個 BarcodeReaderOptions 對象,其中 PageNumbers 設置為特定範圍,限制掃描到相關頁面並減少處理時間。

如何處理多個條碼和 QR 代碼?

生產應用程序通常需要從單個圖像檢測多個條碼或按條碼類型篩選結果。 BarcodeReaderOptions 類公開了控制檢測行為的配置屬性。 將 ExpectMultipleBarcodes 設置為 true 告訴讀取器繼續掃描,直到找到第一個匹配後不停止:

using IronBarCode;

// Configure the reader for multi-barcode detection with type filtering
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;

// Configure the reader for multi-barcode detection with type filtering
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}");
}
$vbLabelText   $csharpLabel

Speed 屬性控制掃描時間與準確性之間的權衡。 ReadingSpeed.Faster 優先於吞吐量,適合批量掃描高質量影像的應用。ReadingSpeed.ExtraSlow 為具有挑戰性的輸入應用更積極的影像校正步驟——低對比、斜角或部分阻塞的代碼。 ReadingSpeed.Balanced 對於大多數應用程序來說,是正確的起點。

BarcodeEncoding 枚舉支持按位組合,因此您可以將掃描限制在與用例相關的符號,而不必因不必要的檢查而削弱性能。

如何從記憶體流中讀取條碼?

文件路徑在大多數場景中效果良好,但一些 .NET MAUI 工作流程會通過內存傳遞圖像數據——例如來自攝像機預覽的捕獲畫框,從 REST API 下載的字節,或進程內生成的圖像數據。 IronBarcode 支持 System.IO.Stream 直接輸入於 BarcodeReader.Read() 重載中:

using IronBarCode;
using System.IO;

// Read a barcode from a MemoryStream (e.g., an in-memory image buffer)
private BarcodeResult[] ReadFromStream(Stream imageStream)
{
    return BarcodeReader.Read(imageStream);
}

// Example: download an image and scan without writing to disk
private async Task<string> ScanDownloadedBarcode(string imageUrl)
{
    using var httpClient = new HttpClient();
    using var stream = await httpClient.GetStreamAsync(imageUrl);
    using var memoryStream = new MemoryStream();

    await stream.CopyToAsync(memoryStream);
    memoryStream.Position = 0;

    var barcodes = BarcodeReader.Read(memoryStream);
    return barcodes.Any() ? barcodes.First().Value : string.Empty;
}
using IronBarCode;
using System.IO;

// Read a barcode from a MemoryStream (e.g., an in-memory image buffer)
private BarcodeResult[] ReadFromStream(Stream imageStream)
{
    return BarcodeReader.Read(imageStream);
}

// Example: download an image and scan without writing to disk
private async Task<string> ScanDownloadedBarcode(string imageUrl)
{
    using var httpClient = new HttpClient();
    using var stream = await httpClient.GetStreamAsync(imageUrl);
    using var memoryStream = new MemoryStream();

    await stream.CopyToAsync(memoryStream);
    memoryStream.Position = 0;

    var barcodes = BarcodeReader.Read(memoryStream);
    return barcodes.Any() ? barcodes.First().Value : string.Empty;
}
$vbLabelText   $csharpLabel

Stream 重載接受任意的 Stream 子類,包括 FileStream 和網路流。 程式庫在內部處理格式檢測,因此您不需要在調用 Read() 之前指定圖像類型。

如何在 MAUI 應用中生成條碼?

IronBarcode 不僅是讀取,也可以處理條碼生成。 BarcodeWriter 類生成圖像文件、Bitmap 對象或 Stream 實例的條碼,您可在 MAUI 視圖中內嵌顯示。 這對於需要打印或共享條碼的庫存應用而言相當有用,同時具有掃描功能:

using IronBarCode;

// Generate a QR code and display it in a MAUI Image control
private async void OnGenerateQrClicked(object sender, EventArgs e)
{
    // Create a QR code barcode
    var qrCode = QRCodeWriter.CreateQrCode(
        value: "https://ironsoftware.com/csharp/barcode/",
        qrCodeSize: 500,
        errorCorrection: QRCodeWriter.QrErrorCorrectionLevel.Medium
    );

    // Save to a temporary file and display
    var tempPath = Path.Combine(FileSystem.CacheDirectory, "generated-qr.png");
    qrCode.SaveAsPng(tempPath);

    GeneratedImageView.Source = ImageSource.FromFile(tempPath);
}
using IronBarCode;

// Generate a QR code and display it in a MAUI Image control
private async void OnGenerateQrClicked(object sender, EventArgs e)
{
    // Create a QR code barcode
    var qrCode = QRCodeWriter.CreateQrCode(
        value: "https://ironsoftware.com/csharp/barcode/",
        qrCodeSize: 500,
        errorCorrection: QRCodeWriter.QrErrorCorrectionLevel.Medium
    );

    // Save to a temporary file and display
    var tempPath = Path.Combine(FileSystem.CacheDirectory, "generated-qr.png");
    qrCode.SaveAsPng(tempPath);

    GeneratedImageView.Source = ImageSource.FromFile(tempPath);
}
$vbLabelText   $csharpLabel

QRCodeWriter 類支持所有四個 QR 糾錯級別(低、中、Quartile、高)、自訂大小和樣式選項,包括前景/背景顏色控制。 對於非 QR 符號,請使用 BarcodeWriter.CreateBarcode() 及適當的 BarcodeEncoding 值。 條碼生成 API 參考 錄有所有支持的輸出格式。

這個條碼掃描程式庫的主要功能是什麼?

IronBarcode 提供了多個在 .NET MAUI 條碼掃描項目中的優勢,區分於像 ZXing.Net.MAUI 這樣的開源替代方案:

IronBarcode 的 .NET MAUI 開發功能
功能詳細
跨平台支持單個 NuGet 套件針對 Android、iOS 和 Windows
多重輸入來源從文件路徑、內存流和 PDF 文件進行掃描
格式覆蓋解碼超過 30 種 1D 和 2D 符號,包括 QR、Data Matrix 和 PDF417
條碼生成生成 QR 代碼和 1D 條碼為 PNG、位圖或流輸出
影像校正自動處理解碼、偏斜和低對比輸入
無原生 SDK 依賴純 .NET 程式庫,無需平台特定的原生綁定

在 .NET MAUI 專案中,"無原生 SDK 依賴"非常重要,因為平台特定的原生程式庫需要每個目標單獨連接步驟。 IronBarcode 完全避免了這種複雜性,這意味著相同的 NuGet 引用為所有三個支持的平台生成工作執行檔,無需額外配置。

欲了解完整的支持條碼格式列表,請參閱 IronBarcode 支持格式文檔。 有關生產部署的定價和授權條款,請查閱 IronBarcode 授權頁面

生產中的條碼掃描最佳實踐是什麼?

將條碼掃描器部署到生產環境需要關注幾個領域,不僅僅是基本的讀取調用。 以下指南介紹了 .NET MAUI 條碼應用程序中最常見的故障點。

選擇正確的讀取速度。 ReadingSpeed.Balanced 可正確處理大多數現實世界的圖像。 保留 ReadingSpeed.ExtraSlow 用於打印文檔或用戶無法重新捕捉的圖像的掃嬸。 避免 ReadingSpeed.ExtraSlow 用於大批量工作流程,因為每次掃描都需要顯著更長的時間。

按預期類型過濾。 如果應用程序只處理 QR 代碼,請設置 ExpectBarcodeTypes = BarcodeEncoding.QRCode。 限制搜索空間可縮短處理時間,並消除背景圖形中存在其他符號的誤報。

僅在需要時使用 ExpectMultipleBarcodes 將其設置為 true 總是會導致讀取器進行額外的通過。 對於單一條碼輸入,請保留默認值 (false),這樣掃描會在找到第一個有效代碼時立即返回。

優雅地處理空結果。 BarcodeReader.Read() 當未檢測到任何條碼時,將返回空數組而不會拋出異常。 在訪問 .Any() 之前進行檢查, First() 並向用戶顯示明確的信息。 提示重試指引("確保條碼光線充足且居中")比一般錯誤更能改善用戶體驗。

緩存選項對象。 在每次掃描中創建 BarcodeReaderOptions 實例會增加分配量。 在類級別構建選項並跨調用重用。

參閱 IronBarcode 問題排查指南條碼讀取器教程 ,以獲得更多診斷掃描故障和優化性能的指南。

你的下一步行動是什麼?

使用 IronBarcode 構建 .NET MAUI 條碼掃描器需要安裝一個單一的 NuGet 套件,配置平台權限,並使用文件路徑或流調用 BarcodeReader.Read()。 同一個 API 針對 Android、iOS 和 Windows,無需平台特定的代碼分支。

要進一步擴展應用程序,請考慮以下資源:

開始您的免費試用以獲得開發授權金鑰,或探索生產部署的授權選項

常見問題解答

什麼是.NET MAUI以及為什麼條形碼掃描嵌入是具有挑戰性的?

.NET MAUI是一個跨平台UI框架,可以從一個代碼庫針對Android、iOS和Windows。條碼掃描具有挑戰性是因為每個平台暴露了不同的相機和存儲API。IronBarcode提供了一個統一的.NET API來為您處理平台差異。

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

IronBarcode支持超過30種條碼符號學,包括QR Code、Code 128、Code 39、EAN-13、EAN-8、UPC-A、UPC-E、Data Matrix、PDF417、Aztec和ITF。使用BarcodeEncoding枚舉來過濾特定格式。

IronBarcode能在.NET MAUI應用中讀取PDF文件上的條碼嗎?

可以。BarcodeReader.ReadPdf()方法會掃描PDF文件的所有頁面並返回一個BarcodeResult集合。每個結果都包含條形碼的值、類型和頁碼。

IronBarcode能在所有.NET MAUI目標平台上運行嗎?

IronBarcode支持一個.NET MAUI專案中的Android、iOS和Windows目標,使用Single NuGet Package。無需平台特定的原生SDK綁定。

如何從單個影像中掃描多個條碼?

在BarcodeReaderOptions中設置ExpectMultipleBarcodes = true,並將選項物件傳遞給BarcodeReader.Read()。該閱讀器將進行附加掃描以在影像中檢測所有條形碼。

ReadingSpeed.Faster和ReadingSpeed.ExtraSlow之間有何區別?

ReadingSpeed.Faster優先考慮吞吐率,對於高質量的影像效果很好。ReadingSpeed.ExtraSlow進行更積極的影像校正,適合棘手的輸入,比如低對比度、已旋轉或部分遮擋的條碼。

IronBarcode能從MemoryStream中讀取條碼嗎?

可以。BarcodeReader.Read()接受System.IO.Stream參數,包括MemoryStream、FileStream和網絡流。這使得可以在不寫入磁碟的情況下掃描內存中的影像數據。

如何在.NET MAUI應用中使用IronBarcode生成QR碼?

使用QRCodeWriter.CreateQrCode()搭配目標值、大小和錯誤校正等級。使用SaveAsPng()儲存結果為PNG文件,並用ImageSource.FromFile()在MAUI Image控制中顯示。

在.NET MAUI Android應用程式中條碼掃描需要的權限是哪些?

在AndroidManifest.xml中添加android.permission.READ_EXTERNAL_STORAGE和android.permission.CAMERA。在iOS中,新增NSPhotoLibraryUsageDescription和NSCameraUsageDescription鍵到Info.plist。

Jordi Bardia
軟體工程師
Jordi 在 Python、C# 和 C++ 上最得心應手,當他不在 Iron Software 展現技術時,便在做遊戲編程。在分担產品测测试,產品開發和研究的责任時,Jordi 為持续的產品改進增值。他说这种多样化的经验使他受到挑战并保持参与, 而这也是他与 Iron Software 中工作一大乐趣。Jordi 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。

鋼鐵支援團隊

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