如何在 .NET MAUI 中對 Android 執行 OCR
.NET MAUI(多平台應用程式 UI)是 Xamarin.Forms 框架的演進版本,旨在利用 .NET 建立適用於 Android、iOS、macOS 和 Windows 的跨平台應用程式。 .NET MAUI 旨在簡化建置可在多個平台上運行的原生使用者介面的過程。
IronOcr.Android 套件為 Android 帶來 OCR 支持!
如何在 .NET MAUI 中使用 Android 上的 IronOCR
- 下載 C# 程式庫以便在 Android 上執行 OCR
- 創建 .NET MAUI App 項目
- 編輯 XAML 文件以顯示激活按鈕和輸出文字
- 編輯相應的 C# 文件以執行 OCR
- 下載示例項目以快速開始
IronOCR 安卓軟體包
IronOcr.Android 套件透過 .NET 跨平台專案在 Android 裝置上啟用 OCR 功能。 不需要原版 IronOCR 軟體包。
使用 NuGet 安裝
安裝 IronOcr.Android 套件
建立一個 .NET MAUI 項目
開啟 Visual Studio,然後按一下「建立新專案」。 搜尋 MAUI,選擇 .NET MAUI 應用程式,然後按一下“下一步”。

包含 IronOCR.Android 庫
可以透過多種方式新增庫。 最簡單的方法或許是使用 NuGet。
- 在 Visual Studio 中,右鍵按一下“依賴項”,然後選擇“管理 NuGet 套件...”。
- 選擇「瀏覽」選項卡,搜尋「IronOcr.Android」。
- 選擇「IronOcr.Android」軟體包,然後點選「安裝」。

為防止與其他平台出現問題,請修改 csproj 文件,使其僅在面向 Android 平台時包含該軟體套件。 為了做到這一點:
-
右鍵點選項目,然後選擇「編輯項目檔案」。
-
建立一個新的 ItemGroup 元素,如下所示:
<ItemGroup Condition="$(TargetFramework.Contains('android')) == true"> </ItemGroup>XML -
將「IronOcr.Android」PackageReference 移到我們剛剛建立的 ItemGroup 中。
上述步驟將防止 "IronOcr.Android" 套件在例如 iOS 平台上被使用(為此,請安裝 IronOcr.iOS)。
編輯“MainActivity.cs”
- 透過導覽至平台 -> Android 開啟「MainActivity.cs」檔案。
- 添加
MainActivity方法並調用Initialize方法。
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.OS;
using IronOcr;
namespace MAUIIronOCRAndroidSample
{
[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
public class MainActivity : MauiAppCompatActivity
{
public MainActivity()
{
// Initialize IronTesseract for OCR purposes
IronTesseract.Initialize(this);
}
}
}Imports Android.App
Imports Android.Content.PM
Imports Android.Runtime
Imports Android.OS
Imports IronOcr
Namespace MAUIIronOCRAndroidSample
<Activity(Theme := "@style/Maui.SplashTheme", MainLauncher := True, ConfigurationChanges := ConfigChanges.ScreenSize Or ConfigChanges.Orientation Or ConfigChanges.UiMode Or ConfigChanges.ScreenLayout Or ConfigChanges.SmallestScreenSize Or ConfigChanges.Density)>
Public Class MainActivity
Inherits MauiAppCompatActivity
Public Sub New()
' Initialize IronTesseract for OCR purposes
IronTesseract.Initialize(Me)
End Sub
End Class
End NamespaceImports Android.App
Imports Android.Content.PM
Imports Android.Runtime
Imports Android.OS
Imports IronOcr
Namespace MAUIIronOCRAndroidSample
<Activity(Theme := "@style/Maui.SplashTheme", MainLauncher := True, ConfigurationChanges := ConfigChanges.ScreenSize Or ConfigChanges.Orientation Or ConfigChanges.UiMode Or ConfigChanges.ScreenLayout Or ConfigChanges.SmallestScreenSize Or ConfigChanges.Density)>
Public Class MainActivity
Inherits MauiAppCompatActivity
Public Sub New()
' Initialize IronTesseract for OCR purposes
IronTesseract.Initialize(Me)
End Sub
End Class
End Namespace編輯“MainPage.xaml”
編輯 XAML 文件,使其顯示一個按鈕和一個標籤,用於顯示 OCR 結果。 舉例來說
<?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="MAUIIronOCRAndroidSample.MainPage">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button
Text="Import File"
Clicked="ReadFileOnImport"
Grid.Row="0"
HorizontalOptions="Center"
Margin="20, 20, 20, 10"/>
<ScrollView
Grid.Row="1"
BackgroundColor="LightGray"
Padding="10"
Margin="10, 10, 10, 30">
<Label x:Name="OutputText"/>
</ScrollView>
</Grid>
</ContentPage>
編輯“MainPage.xaml.cs”
首先,創建 IronTesseract 物件的實例。 確保在類中初始化 IronTesseract,如下面的代碼所示。 在方法內部實例化它可能無效,並可能導致意想不到的錯誤。
接下來,使用 FilePicker.PickAsync 方法選擇文件,然後從 FileResult 打開讀取流。 創建一個新的 OcrInput 物件並將圖像載入其中。 使用 Tesseract 實例對圖像進行 OCR,並檢索文本。 最後,將結果文字顯示在標籤中。
using IronOcr;
using Microsoft.Maui.Controls;
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
namespace MAUIIronOCRAndroidSample
{
public partial class MainPage : ContentPage
{
// Initialize IronTesseract once in a class
private readonly IronTesseract ocrTesseract = new IronTesseract();
public MainPage()
{
InitializeComponent();
// Apply License key if required
IronOcr.License.LicenseKey = "IRONOCR.MYLICENSE.KEY.1EF01";
}
private async void ReadFileOnImport(object sender, EventArgs e)
{
try
{
// Configure the file picker
var options = new PickOptions
{
PickerTitle = "Please select a file"
};
// Await user's file selection
var result = await FilePicker.PickAsync(options);
if (result != null)
{
using var stream = await result.OpenReadAsync();
// Instantiate OcrInput
using var ocrInput = new OcrInput();
// Load image stream for OCR processing
ocrInput.LoadImage(stream);
// Perform OCR
var ocrResult = ocrTesseract.Read(ocrInput);
// Display extracted text
OutputText.Text = ocrResult.Text;
}
}
catch (Exception ex)
{
// Log and handle exceptions
Debug.WriteLine(ex);
}
}
}
}using IronOcr;
using Microsoft.Maui.Controls;
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
namespace MAUIIronOCRAndroidSample
{
public partial class MainPage : ContentPage
{
// Initialize IronTesseract once in a class
private readonly IronTesseract ocrTesseract = new IronTesseract();
public MainPage()
{
InitializeComponent();
// Apply License key if required
IronOcr.License.LicenseKey = "IRONOCR.MYLICENSE.KEY.1EF01";
}
private async void ReadFileOnImport(object sender, EventArgs e)
{
try
{
// Configure the file picker
var options = new PickOptions
{
PickerTitle = "Please select a file"
};
// Await user's file selection
var result = await FilePicker.PickAsync(options);
if (result != null)
{
using var stream = await result.OpenReadAsync();
// Instantiate OcrInput
using var ocrInput = new OcrInput();
// Load image stream for OCR processing
ocrInput.LoadImage(stream);
// Perform OCR
var ocrResult = ocrTesseract.Read(ocrInput);
// Display extracted text
OutputText.Text = ocrResult.Text;
}
}
catch (Exception ex)
{
// Log and handle exceptions
Debug.WriteLine(ex);
}
}
}
}Imports IronOcr
Imports Microsoft.Maui.Controls
Imports System
Imports System.Diagnostics
Imports System.IO
Imports System.Threading.Tasks
Namespace MAUIIronOCRAndroidSample
Partial Public Class MainPage
Inherits ContentPage
' Initialize IronTesseract once in a class
Private ReadOnly ocrTesseract As New IronTesseract()
Public Sub New()
InitializeComponent()
' Apply License key if required
IronOcr.License.LicenseKey = "IRONOCR.MYLICENSE.KEY.1EF01"
End Sub
Private Async Sub ReadFileOnImport(ByVal sender As Object, ByVal e As EventArgs)
Try
' Configure the file picker
Dim options = New PickOptions With {
.PickerTitle = "Please select a file"
}
' Await user's file selection
Dim result = Await FilePicker.PickAsync(options)
If result IsNot Nothing Then
Using stream = Await result.OpenReadAsync()
' Instantiate OcrInput
Using ocrInput = New OcrInput()
' Load image stream for OCR processing
ocrInput.LoadImage(stream)
' Perform OCR
Dim ocrResult = ocrTesseract.Read(ocrInput)
' Display extracted text
OutputText.Text = ocrResult.Text
End Using
End Using
End If
Catch ex As Exception
' Log and handle exceptions
Debug.WriteLine(ex)
End Try
End Sub
End Class
End NamespaceImports IronOcr
Imports Microsoft.Maui.Controls
Imports System
Imports System.Diagnostics
Imports System.IO
Imports System.Threading.Tasks
Namespace MAUIIronOCRAndroidSample
Partial Public Class MainPage
Inherits ContentPage
' Initialize IronTesseract once in a class
Private ReadOnly ocrTesseract As New IronTesseract()
Public Sub New()
InitializeComponent()
' Apply License key if required
IronOcr.License.LicenseKey = "IRONOCR.MYLICENSE.KEY.1EF01"
End Sub
Private Async Sub ReadFileOnImport(ByVal sender As Object, ByVal e As EventArgs)
Try
' Configure the file picker
Dim options = New PickOptions With {
.PickerTitle = "Please select a file"
}
' Await user's file selection
Dim result = Await FilePicker.PickAsync(options)
If result IsNot Nothing Then
Using stream = Await result.OpenReadAsync()
' Instantiate OcrInput
Using ocrInput = New OcrInput()
' Load image stream for OCR processing
ocrInput.LoadImage(stream)
' Perform OCR
Dim ocrResult = ocrTesseract.Read(ocrInput)
' Display extracted text
OutputText.Text = ocrResult.Text
End Using
End Using
End If
Catch ex As Exception
' Log and handle exceptions
Debug.WriteLine(ex)
End Try
End Sub
End Class
End Namespace最後,在 .csproj 文件中,確保僅為 Android 構建專案。 由於我們新增的軟體包僅適用於 Android,因此為所有平台建置專案將會失敗。
運行專案
這將向您展示如何運行專案並執行 OCR。
下載 .NET MAUI 應用程式項目
您可以下載本指南的完整程式碼。它以壓縮檔案的形式提供,您可以在 Visual Studio 中將其作為 .NET MAUI 應用程式專案開啟。
在 Avalonia 中使用 IronOcr.Android
與 MAUI 類似,IronOcr.Android 可以按照上述相同的設定用於 Avalonia 專案。
如果您想在 iOS 上執行 OCR,請導航到以下文章以了解更多信息:「如何在 .NET MAUI 中在 iOS 上執行 OCR」
常見問題
什麼是IronOCR Android套件?
IronOCR.Android套件在Android設備上使用.NET跨平台專案啟用OCR功能。它特別設計用於整合與.NET MAUI架構進行Android開發。
如何使用NuGet安裝IronOCR.Android套件?
開啟Visual Studio,右鍵點選'Dependencies'並選擇'Manage NuGet Packages'。在'Browse'標籤下,搜尋'IronOcr.Android',選擇套件,然後點選'Install'。
我能否在其他平台上使用IronOCR.Android?
IronOCR.Android專為Android平台量身打造。若需要跨平台支援,如iOS,您應該使用特定平台版本,如IronOcr.iOS。
如何為IronOCR配置.NET MAUI專案?
首先在Visual Studio中創建一個.NET MAUI應用程式專案。透過NuGet包括IronOCR.Android程式庫,並修改.csproj檔案以特定針對Android平台。
在.NET MAUI應用程式中執行OCR需要哪些步驟?
要執行OCR,請在您的'MainActivity.cs'中初始化IronTesseract,配置您的XAML檔案以進行UI,並在'MainPage.xaml.cs'中處理檔案輸入和OCR處理。
IronOCR如何處理C#中的檔案選擇和OCR?
IronOCR在.NET MAUI應用程式中使用FilePicker.PickAsync方法來進行檔案選擇。用戶選擇檔案後,IronTesseract處理影像以執行OCR並提取文字數據。
專案檔案中需要什麼來確保它僅針對Android?
在.csproj文件中,建立一個ItemGroup,使用條件來針對Android,使用<ItemGroup Condition="$(TargetFramework.Contains('android')) == true">以確保只使用'IronOcr.Android'封裝。
如何下載使用IronOCR的完整範例專案?
您可以從提供的指南鏈接下載完整的.NET MAUI應用程式專案,包含IronOCR.Android設置,這包括一個用於Visual Studio的壓縮檔案。
在Avalonia專案中可以使用IronOCR嗎?
可以,IronOCR.Android可以在Avalonia專案中使用,設置步驟類似於.NET MAUI應用程式。
如何在MAUI專案中初始化IronTesseract?
在您的'MainActivity'中,通過調用IronTesseract.Initialize(this);初始化IronTesseract,以準備在您的Android應用中進行OCR操作。
Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。