如何在 .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 功能。 不需要 vanilla 版的 IronOCR 套件。

Install-Package IronOcr.Android
C# 的 NuGet PDF 程式庫

使用 NuGet 安裝

Install-Package 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"

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

您可以下載本指南的完整程式碼。它是作為壓縮文件來的,您可以在 Visual Studio 中將其作為 .NET MAUI 應用程式專案打開。

點選這裡下載專案。

在 Avalonia 中使用 IronOcr.Android

類似於 MAUI,可以將 IronOcr.Android 用於 Avalonia 專案,設置方式如上所述。

如果您想在 iOS 上執行 OCR,請前往以下文章了解更多:"如何在 .NET MAUI 上執行 iOS 的 OCR"

常見問題

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

要在.NET MAUI上使用 IronOcr.Android 套件在 Android 上執行 OCR,請在 Visual Studio 中通過 NuGet 安裝 IronOcr.Android 套件。使用 IronTesseract 類處理影像並提取文字。確保您的專案配置正確地將目標設定為 Android,適當修改 .csproj 文件。

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

IronOcr.Android 套件專門設計用於在 .NET MAUI 專案內為 Android 裝置提供 OCR 功能。它簡化了面向 Android 的跨平台應用中的文字識別功能整合。

如何為 Android OCR 配置 .NET MAUI 專案?

通過 NuGet 安裝 IronOcr.Android 套件來配置您的 .NET MAUI 專案。通過建立新的 ItemGroup 元素並將 IronOcr.Android PackageReference 移動到其中,調整 .csproj 文件以將目標設為 Android。這避免了其它平台的構建問題。

MainActivity.cs 中 OCR 設置需要進行哪些修改?

在平台 -> Android 下的 MainActivity.cs 文件中新增 MainActivity 方法,並從 IronTesseract 調用 Initialize 方法。這設置了處理影像中文字所需的 OCR 能力。

如何編輯 MainPage.xaml 以整合 OCR 功能?

編輯 MainPage.xaml 以包含用於導入文件的按鈕和顯示 OCR 結果的標籤。定義必要的 UI 元素,以便與 OCR 處理邏輯進行互動並有效地管理使用者輸入。

如果在 OCR 處理期間遇到錯誤,我應該怎麼做?

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

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

是的,可以在 Avalonia 專案中使用 IronOcr.Android 套件,設置過程與 .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 文件。這可以防止構建其他平台時發生衝突。

如何通過IronOCR提高OCR結果的準確性?

為了提高IronOCR的OCR準確性,確保高品質輸入圖片,使用適當的語言包,並利用該程式庫的圖像預處理功能。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

準備開始了嗎?
Nuget 下載 6,151,372 | 版本: 2026.7 剛剛發布
Still Scrolling Icon

還在滾動?

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