如何在 .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);
        }
    }
}
$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);
            }
        }
    }
}
$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 識別?

若要在 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 庫,可透過指南中的連結下載。此專案以壓縮檔案的形式提供,可直接在 Visual Studio 中開啟。

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

為確保 IronOcr.Android 套件僅面向 Android 平台,請修改 .csproj 文件,建立一個針對 Android 的條件 ItemGroup,並將 IronOcr.Android PackageReference 移至其中。這樣可以避免在建構其他平台版本時發生衝突。

柯蒂斯·週
技術撰稿人

Curtis Chau擁有卡爾頓大學電腦科學學士學位,專長於前端開發,精通Node.js、TypeScript、JavaScript和React。他熱衷於打造直覺美觀的使用者介面,喜歡使用現代框架,並擅長撰寫結構清晰、視覺效果出色的使用者手冊。

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

準備好開始了嗎?
Nuget 下載 5,299,091 | 版本: 2025.12 剛剛發布