如何在 .NET MAUI 中對 Android 執行 OCR

This article was translated from English: Does it need improvement?
Translated
View the article in English
Android related to 如何在 .NET MAUI 中對 Android 執行 OCR

.NET MAUI(多平台應用程式 UI)是 Xamarin.Forms 框架的演進版本,旨在利用 .NET 建立適用於 Android、iOS、macOS 和 Windows 的跨平台應用程式。 .NET MAUI 旨在簡化建置可在多個平台上運行的原生使用者介面的過程。

IronOcr.Android軟體包為Android帶來了OCR支援!

IronOCR 安卓軟體包

IronOcr.Android 套件透過 .NET 跨平台專案在 Android 裝置上啟用 OCR 功能。 不需要原版 IronOCR 軟體包。

安裝 IronOcr.Android 套件
C# NuGet PDF 庫

使用 NuGet 安裝

安裝 IronOcr.Android 套件

建立一個 .NET MAUI 項目

開啟 Visual Studio,然後按一下"建立新專案"。 搜尋 MAUI,選擇 .NET MAUI 應用程序,然後按一下"下一步"。

建立 .NET MAUI 應用程式項目

包含 IronOCR.Android 庫

可以透過多種方式新增庫。 最簡單的方法或許是使用 NuGet。

  1. 在 Visual Studio 中,右鍵按一下"依賴項",然後選擇"管理 NuGet 套件..."。
  2. 選擇"瀏覽"選項卡,搜尋"IronOcr.Android"。
  3. 選擇"IronOcr.Android"軟體包,然後點選"安裝"。

下載 IronOcr.Android 套件

為防止與其他平台出現問題,請修改 csproj 文件,使其僅在面向 Android 平台時包含該軟體套件。 為了做到這一點:

  1. 右鍵點選項目,然後選擇"編輯項目檔案"。
  2. 建立一個新的 ItemGroup 元素,如下所示:

    <ItemGroup Condition="$(TargetFramework.Contains('android')) == true">
    </ItemGroup>
    <ItemGroup Condition="$(TargetFramework.Contains('android')) == true">
    </ItemGroup>
    XML
  3. 將"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);
        }
    }
}
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 Namespace
$vbLabelText   $csharpLabel

編輯"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>
<?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>
XML

編輯"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.AddImage(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.AddImage(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
					Dim stream = Await result.OpenReadAsync()
					' Instantiate OcrInput
					Dim ocrInput As New OcrInput()
					' Load image stream for OCR processing
					ocrInput.AddImage(stream)
					' Perform OCR
					Dim ocrResult = ocrTesseract.Read(ocrInput)
					' Display extracted text
					OutputText.Text = ocrResult.Text
				End If
			Catch ex As Exception
				' Log and handle exceptions
				Debug.WriteLine(ex)
			End Try
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

最後,在.csproj檔案中,確保你只為 Android 建置專案。 由於我們新增的軟體包僅適用於 Android,因此為所有平台建置專案將會失敗。

運行專案

這將向您展示如何運行專案並執行 OCR。

Execute .NET MAUI App project

下載 .NET MAUI 應用程式項目

您可以下載本指南的完整程式碼。它以壓縮檔案的形式提供,您可以在 Visual Studio 中將其作為 .NET MAUI 應用程式專案開啟。

點擊此處下載項目。

在 Avalonia 中使用 IronOcr.Android

與 MAUI 類似,IronOcr.Android 可以按照上述相同的設定用於 Avalonia 專案。

如果您想在 iOS 上執行 OCR,請參閱以下文章以了解更多資訊:"如何在 .NET MAUI 中對 iOS 執行 OCR "

常見問題解答

如何在 .NET MAUI 應用程式中執行 Android 上的 OCR?

若要使用 .NET MAUI 在 Android 上執行 OCR,請在 Visual Studio 中透過 NuGet 安裝 IronOcr.Android 套件。使用 IronTesseract 類別來處理影像並擷取文字。透過適當修改 .csproj 檔案,確保您的專案已設定為針對 Android。

IronOcr.Android 套件的目的是什麼?

IronOcr.Android 套件專門設計用來在 .NET MAUI 專案中為 Android 裝置帶來 OCR 功能。它簡化了針對 Android 的跨平台應用程式中文字辨識功能的整合。

如何為 Android OCR 設定 .NET MAUI 專案?

透過 NuGet 安裝 IronOcr.Android 套件,配置您的 .NET MAUI 專案。透過建立新的 ItemGroup 元素並將 IronOcr.Android PackageReference 移至其中,調整 .csproj 檔案以針對 Android。這可避免其他平台的建立問題。

為了進行 OCR 設定,MainActivity.cs 中需要進行哪些修改?

在 Platforms -> Android 下的 MainActivity.cs 檔案中,新增 MainActivity 方法,並呼叫 IronTesseract 的 Initialize 方法。這會設定從影像處理文字所需的 OCR 功能。

如何編輯 MainPage.xaml 以納入 OCR 功能?

編輯 MainPage.xaml,加入匯入檔案的按鈕和顯示 OCR 結果的標籤。定義必要的 UI 元素,以便與 OCR 處理邏輯互動,並有效管理使用者輸入。

如果在 OCR 處理過程中遇到錯誤,該怎麼辦?

在您的 OCR 處理程式碼周圍使用 try-catch 區塊來處理異常。使用 Debug.WriteLine 或其他記錄機制記錄任何錯誤,以協助診斷和修正問題。

是否可以在 Avalonia 專案中使用 IronOcr.Android 套件?

是的,IronOcr.Android 套件可在 Avalonia 專案中使用,其設定過程與 .NET MAUI 類似。請相應調整專案配置以啟用 OCR 功能。

哪裡可以找到使用 .NET MAUI 的 Android OCR 完整範例專案?

使用 .NET MAUI 中的 IronOCR 函式庫進行 Android OCR 的完整範例專案,可透過指南中提供的連結下載。該專案為壓縮檔,可在 Visual Studio 中開啟。

如何確保 IronOcr.Android 套件在多平台專案中只針對 Android?

為了確保 IronOcr.Android 套件只針對 Android,請修改 .csproj 檔案,為 Android 建立一個有條件的 ItemGroup,並將 IronOcr.Android PackageReference 移至其中。這可避免為其他平台建置時發生衝突。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。

準備好開始了嗎?
Nuget 下載 5,167,857 | Version: 2025.11 剛發表