如何在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是微軟的跨平台框架,用於從單一共享程式碼庫使用 C# 和 XAML 建立原生行動和桌面應用程式。
與ZXing.Net.MAUI等基於相機的解決方案不同,IronBarcode 不需要特殊配置,因為 ZXing.Net.MAUI 需要 CameraView 控制設定和 MauiProgram.cs 註冊。 您的 MauiProgram.cs 仍處於預設範本狀態。 這樣可以避免啟動程式碼中涉及第三方處理程序註冊,並減少啟動時初始化錯誤的發生範圍。
若要安裝 IronBarcode,請在軟體套件管理器控制台中執行下列命令:
Install-Package BarCode
Install-Package BarCode
這個單一軟體包即可提供條碼掃描、二維碼識別、多條碼偵測和條碼產生功能。 無需其他依賴項。
若要在生產環境中啟動 IronBarcode,請將您的許可證金鑰設定到 App.xaml.cs 或 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"
您可以從IronBarcode 授權頁面取得金鑰,或從免費試用許可證開始。
基於影像的掃描的權限有何不同?
傳統的基於攝影機的條碼掃描器需要在平台清單中明確授權。 在 Android 系統中,您需要新增 AndroidManifest.xml:
<uses-permission android:name="android.permission.CAMERA" /><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
在 iOS 上,您在 Info.plist 中聲明 NSCameraUsageDescription。 在執行時間處理被拒絕的權限會增加容易被忽略的錯誤路徑。
因為 IronBarcode 是從檔案流而不是相機預覽中讀取數據,所以您只需要存取檔案系統。 在Windows系統中,此權限會自動被授予。 在 Android 和 iOS 上,FilePicker 會在使用者選擇映像時處理使用者同意—無需手動請求權限。
MAUI條碼掃描器最適合使用哪種XAML介面?
一個極簡的介面——一個影像選擇按鈕、一個影像顯示區域和一個結果標籤——就能滿足大多數條碼掃描場景的需求。 以下 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>
此佈局提供了一個用於觸發文件選擇器的按鈕、一個用於顯示所選圖像的區域以及一個用於顯示解碼後的條碼值的標籤。 它在所有 .NET MAUI 目標平台上都能正確渲染,無需針對特定平台進行調整。
對於生產應用程序,請考慮將 ResultsLabel 替換為 CollectionView,以便在可捲動清單中顯示多個條碼結果,尤其是在掃描包含多個條碼的文件時。
如何在.NET MAUI中掃描影像檔案中的條碼?
MainPage.xaml.cs 中的程式碼隱藏處理影像選擇和條碼讀取。 BarcodeReader.Read 接受檔案路徑並傳回一個 BarcodeResults 集合。 集合中的每個項目都顯示條碼 Value、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
BarcodeReader.Read 處理給定路徑下的文件,自動偵測所有存在的條碼符號,並立即傳回結果。 此方法支援所有主要的 1D 和 2D 條碼格式,包括 Code 128、Code 39、QR Code、Data Matrix、PDF417 和 EAN-13。
!a href="/static-assets/barcode/blog/net-maui-scan-barcode/net-maui-scan-barcode-1.webp">.NET MAUI 使用強大的條碼掃描器函式庫在 Windows 應用程式中掃描條碼:圖片 1 - 掃描條碼輸出
FilePicker.PickAsync 呼叫將選擇器限制為映像類型,因此使用者不會意外選擇非映像檔。 如果 result 是 null,則表示使用者已取消 -- 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
這種模式適用於簡單的確認流程。 對於需要對解碼值執行操作的應用程式(例如,在條碼庫存管理系統中透過條碼來尋找產品),請直接從 OnSelectImage 處理程序將 barcodes 集合傳遞給您的業務邏輯層。
如何掃描多個條碼並調整偵測速度?
當影像中包含多個條碼時,IronBarcode 預設會偵測所有條碼。 為了在知道預期格式的情況下獲得更好的效能,請在呼叫 BarcodeReader.Read 之前配置 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
!a href="/static-assets/barcode/blog/net-maui-scan-barcode/net-maui-scan-barcode-2.webp">.NET MAUI 使用強大的條碼掃描器函式庫在 Windows 應用程式中掃描條碼:圖片 2 - 掃描多個 BarCode 的輸出。
ExpectBarcodeTypes 屬性將偵測引擎的範圍縮小到指定的符號系統。 設定 Speed 至 ReadingSpeed.Faster 適用於高對比、無失真的影像。 ReadingSpeed.Detailed 套用額外的影像校正流程,並處理旋轉、傾斜和低解析度輸入,但代價是需要額外的處理時間。
ExpectMultipleBarcodes = true 告訴讀者在第一次配對後繼續掃描,而不是提前返回。 在單條碼場景下,省略此選項可使每次掃描節省幾毫秒時間。
這種配置使得掃描器適用於各種應用:零售應用程式讀取產品條碼,倉庫工具處理出貨照片上的列印條碼標籤,或文件工作流程從上傳的發票中提取二維碼。
如何處理高難度或低品質圖片?
生產過程中使用的圖片很少是完美無瑕的。在強光下拍攝的倉庫照片、電子郵件用戶端的螢幕截圖以及掃描的文件都會引入雜訊、壓縮偽影和幾何失真。 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)
SharpenFilter 從壓縮或失焦的捕捉恢復邊緣定義。 ContrastFilter 在光線不均勻時很有用。 DenoiseFilter 減少低解析度掃描產生的散斑。 將這些過濾器與 ReadingSpeed.Detailed 結合使用,可以最大限度地提高對困難材料的閱讀率。
對於接受用戶從各種來源上傳圖像的 .NET MAUI 應用程序,默認情況下應用保守的過濾器,並在第二次重試時升級到更積極的糾正措施,可以在常見情況下改善用戶體驗,而不會增加明顯的延遲。 您也可以將 Uri 或 byte[] 直接傳遞給 BarcodeReader.Read,這在圖片來自網路回應而不是檔案系統時非常有用。 如需更多輸入來源範例,請參閱IronBarcode 操作指南。
為什麼基於影像的掃描適合 .NET MAUI 應用程式?
透過 CameraView 控制進行即時攝影機掃描需要平台特定的權限授予、攝影機預覽的生命週期管理以及焦點事件的處理。 在 iOS 上,這也意味著配置 AVCaptureSession; 在 Android 上,CameraX。 每個平台都有其自身的故障模式。
基於影像的掃描完全消除了這類擔憂。 IronBarcode API 參考顯示 BarcodeReader.Read 接受檔案路徑、Stream、Bitmap 或 byte[] -- 您的 MAUI 應用程式可以產生的任何表示形式。 這意味著無論圖像來自 FilePicker、網頁下載、渲染為點陣圖的 PDF 頁面或電子郵件附件,相同的掃描邏輯都能正常運作。
由於相機硬體保持關閉狀態,因此電池消耗量更低。 即時預覽不會出現介面閃爍,也無需在應用程式暫停和恢復期間管理相機生命週期事件。 在平板電腦和桌上型電腦等裝置中,即時取景器很少適用,因此基於影像的解碼是自然的預設選擇,而非妥協之舉。無論裝置類型為何,使用者都可以使用相同的 FilePicker 呼叫開啟雲端儲存、本機資料夾或相機膠卷中的檔案。
對於使用者拍攝條碼標籤並上傳的工作流程(在ASP.NET 條碼掃描器 Web 應用程式中很常見),同一個 BarcodeReader.Read 呼叫在行動用戶端和伺服器上都有效,無需維護兩個掃描實作。
IronBarcode 與 ZXing.Net.MAUI 相比如何?
ZXing.Net.MAUI針對即時相機掃描,當產品需要即時取景器回饋時,它能很好地發揮作用。 它需要 CameraView 整合、平台處理程序註冊和運行時權限請求。
IronBarcode 的目標是基於文件和基於流的解碼,涵蓋了大多數企業文件工作流程。 它支援更廣泛的符號體系,包括PDF417 、 Data Matrix和Code 128 ,並提供 ZXing 沒有提供的影像濾鏡預處理功能。 對於用戶拍攝或上傳圖像而不是即時掃描物品的應用場景,IronBarcode 是更直接的選擇。
如果您的應用程式除了基於檔案的解碼之外還需要即時攝影機掃描,您可以將這兩個庫結合起來:ZXing.Net.MAUI 用於取景器工作流程,IronBarcode 用於批次檔案處理。
下一步計劃是什麼?
使用 IronBarcode 建立 .NET MAUI 條碼掃描器只需要不到 30 行 C# 程式碼。 圖像檔案方法使您的 MAUI 程式碼庫無需相機權限邏輯和特定於平台的初始化,並且相同的掃描呼叫在 Windows、Android 和 iOS 上運行完全相同。
IronBarcode API 文件涵蓋了其他功能:從 PDF 文件中讀取條碼、批量處理多個圖像、編寫自訂圖像過濾器以及在讀取條碼的同時產生條碼。 功能概述列出了所有支援的符號體系和格式。
您可以開始免費試用,在您的專案中測試 IronBarcode,或在準備好進行生產部署時購買許可證。
!{--01001100010010010100001001010010010000010101001001011001010111110100011101000101010101 01000101111101010011010101000100000101010010010101000100010101000100010111110101011101001000110 1010101000100100001011111010100000101001001001111010001000101010101010000110101010100101010101011 10101010001010010010010010010000010100110001011111010000100100110001001111101000011010010111111010000110100101110--
常見問題解答
如何在.NET MAUI中創建無相機的條碼掃描器?
通過NuGet安裝IronBarcode(`Install-Package BarCode`),然後使用從`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和Data Matrix),並提供針對低質量輸入的圖像濾鏡預處理。
如何改善在模糊或低質量圖像上的條碼檢測?
在`BarcodeReaderOptions`中添加`ImageFilterCollection`,包括`SharpenFilter`、`ContrastFilter`和`DenoiseFilter`,並設置`Speed = ReadingSpeed.Detailed`。這將在解碼前應用圖像修正。
IronBarcode在.NET MAUI中支持哪些條碼格式?
IronBarcode支持所有主要的1D和2D符號:Code 128、Code 39、QR Code、Data Matrix、PDF417、EAN-13、EAN-8、UPC-A、UPC-E、Aztec等。完整列表請參見IronBarcode功能頁面。

