如何在 .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 App,然后点击“下一步”。

包含 IronOCR.Android 库
这个库可以通过多种方式添加。 最简单的方法可能是使用NuGet。
- 在Visual Studio中,右键点击“Dependencies”并选择“管理NuGet Packages ...”。
- 选择“浏览”选项卡,搜索“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包在使用.NET跨平台项目的Android设备上启用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 App项目。通过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 Condition="$(TargetFramework.Contains('android')) == true"> 创建一个带有条件的 ItemGroup,以确保仅使用 'IronOcr.Android' 包。
如何下载使用IronOCR的完整示例项目?
您可以从提供的指南链接下载完整的.NET MAUI App项目,其中包含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。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。