如何在 .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(多平台應用程式使用者介面)是 Xamarin.Forms 框架的演進版本,旨在透過 .NET 為 Android、iOS、macOS 和 Windows 建立跨平台應用程式。 .NET MAUI 旨在簡化建置可在多平台運行的原生使用者介面的流程。

IronOcr.Android 套件為 Android 帶來 OCR 支援!

IronOCR Android 套件

IronOcr.Android 套件可透過 .NET 跨平台專案,在 Android 裝置上啟用 OCR 功能。 無需翻譯標準版 IronOCR 套件。

Install-Package IronOcr.Android
用於 PDF 的 C# NuGet 函式庫

透過 NuGet 安裝

Install-Package IronOcr.Android

建立一個 .NET MAUI 專案

開啟 Visual Studio 並點擊"建立新專案"。 搜尋 MAUI,選擇 .NET MAUI App 並點擊"下一步"。

建立 .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 等平台上使用(若需在 iOS 平台上使用,請改為安裝 IronOcr.iOS)。

編輯"MainActivity.cs"

  • 請導航至"Platforms"→"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 應用程式專案

您可以下載本指南的完整程式碼。該檔案以 ZIP 形式提供,您可在 Visual Studio 中將其開啟為 .NET MAUI App 專案。

點擊此處下載專案。

在 Avalonia 中使用 IronOcr.Android

與 MAUI 類似,IronOcr.Android 可在 Avalonia 專案中使用,其設定方式與上述說明相同。

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

常見問題

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

若要在 Android 上使用 .NET MAUI 執行 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 專案。請修改 .csproj 檔案以針對 Android 平台進行設定,方法是建立一個新的 ItemGroup 元素,並將 IronOcr.Android PackageReference 移入其中。此舉可避免其他平台出現建置問題。

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

在 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 的完整範例專案?

您可透過指南中提供的連結,下載一個完整的 Android OCR 範例專案,該專案採用 .NET MAUI 中的 IronOCR 程式庫。此專案以 ZIP 檔形式提供,可直接在 Visual Studio 中開啟。

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

為確保 IronOcr.Android 套件僅針對 Android 平台,請修改 .csproj 檔案,建立一個針對 Android 的條件式 ItemGroup,並將 IronOcr.Android PackageReference 移入其中。此舉可避免在建構其他平台時發生衝突。

如何使用 IronOCR 提升 OCR 結果的準確性?

若要提升 IronOCR 的 OCR 準確度,請確保輸入影像品質優良、使用適當的語言套件,並善用該程式庫的影像預處理功能。

Curtis Chau
技術撰稿人

Curtis Chau 擁有卡爾頓大學(Carleton University)的電腦科學學士學位,專精於前端開發,並精通 Node.js、TypeScript、JavaScript 及 React。他熱衷於打造直觀且美觀的用戶介面,喜歡運用現代框架,並創建結構完善、視覺上吸引人的手冊。

除了開發工作之外,Curtis 對物聯網(IoT)抱有濃厚興趣,致力於探索整合硬體與軟體的創新方法。閒暇時,他喜歡玩遊戲和開發 Discord 機器人,將對科技的熱愛與創意相結合。

準備開始了嗎?
Nuget 下載 5,896,332 | 版本: 2026.5 just released
Still Scrolling Icon

還在往下捲動嗎?

想要快速確認成果嗎? PM > Install-Package IronOcr
執行範例 觀看您的圖片轉為可搜尋文字。