如何在 .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 套件

<! -- NuGet 函式庫下載指令標籤 ::開始 -->

用於 PDF 的 C# NuGet 庫
### 使用 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?

要在 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 bots,將他對技術的熱愛與創意結合。

準備好開始了嗎?
Nuget 下載 5,384,824 | 版本: 2026.2 剛剛發布