如何在.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軟體包。

Install-PackageIronOcr.Android 軟體包
用於 PDF 的 C# NuGet庫
### 使用NuGet安裝
Install-PackageIronOcr.Android 軟體包

建立一個.NET MAUI項目

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

創建.NET MAUI應用程式專案

包含IronOcr.Android 庫

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

  1. 在 Visual Studio 中,右鍵點選"依賴項",然後選擇"管理NuGet套件..."。
  2. 選擇"瀏覽"選項卡,搜尋"IronOCR"。
  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"套件引用移到我們剛剛建立的 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

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

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

常見問題解答

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

要在 Android 上使用 .NET MAUI 執行 OCR,請在 Visual Studio 中通過 NuGet 安裝 IronOcr.Android 套件。使用 IronTesseract 類處理圖片並提取文本。確保您的項目已正確配置為目標 Android,必要時修改 .csproj 文件。

IronOcr.Android 套件的用途是什麼?

IronOcr.Android 套件專為在 .NET MAUI 項目中將 OCR 功能引入 Android 設備而設計。它簡化了針對 Android 的跨平台應用中的文本識別功能集成。

如何為 Android OCR 配置 .NET MAUI 項目?

通過 NuGet 安裝 IronOcr.Android 套件來配置您的 .NET MAUI 項目。創建新的 ItemGroup 元素並將 IronOcr.Android PackageReference 移至其中,以調整 .csproj 文件的目標 Android。這避免了其他平台的構建問題。

在 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 完整示例項目?

使用 IronOCR 庫的 .NET MAUI Android OCR 完整示例項目可以通過指南中提供的鏈接下載。該項目作為壓縮文件提供,準備好在 Visual Studio 中打開。

如何確保 IronOcr.Android 套件僅針對 Android 在多平台項目中?

要確保 IronOcr.Android 套件僅針對 Android,請通過創建條件的 Android ItemGroup 並將 IronOcr.Android PackageReference 移入其中來修改 .csproj 文件。這防止了構建其他平台時的衝突。

Curtis Chau
技術作家

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

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

準備好開始了嗎?
Nuget 下載 5,556,263 | 版本: 2026.3 剛剛發布
Still Scrolling Icon

還在捲動嗎?

想要快速證明? PM > Install-Package IronOcr
執行範例 觀看您的圖片變成可搜尋的文字。