.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 Android パッケージ

IronOcr.Android パッケージは、.NET クロスプラットフォーム プロジェクトを介して Android デバイスで OCR 機能を有効にします。 標準の IronOCR パッケージは必要ありません。

インストールパッケージ IronOcr.Android
PDF用C# NuGetライブラリ

Install with NuGet

インストールパッケージ IronOcr.Android

.NET MAUIプロジェクトを作成する

Visual Studioを開き、"新しいプロジェクトを作成"をクリックします。 MAUIを検索し、.NET MAUIアプリを選択して"次へ"をクリックします。

! .NET MAUI アプリプロジェクトを作成する

IronOCR.Androidライブラリを組み込む

ライブラリを追加する方法はいくつかあります。 最も簡単なのは、おそらくNuGetを使用することです。

  1. Visual Studio内で"Dependencies"を右クリックし、"Manage NuGet Packages ..."を選択します。 2."参照"タブを選択し、"IronOcr.Android"を検索します。
  2. "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クラス内で 1 回初期化されていることを確認します。 メソッド内でインスタンス化しても効果がなく、予期しないエラーが発生する可能性があります。

次に、 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アプリプロジェクトとして開くことができます。

プロジェクトをダウンロードするにはここをクリックしてください。

AvaloniaでIronOcr.Androidを使用する

MAUI と同様に、IronOcr.Android は上記と同じ設定で Avalonia プロジェクトで使用できます。

iOS で OCR を実行する場合は、次の記事を参照して詳細を確認してください: " .NET MAUI で iOS で OCR を実行する方法"

よくある質問

どうすれば、.NET MAUI アプリケーションで Android 上で OCR を実行できますか?

.NET MAUI で Android 上で OCR を実行するには、Visual Studio の NuGet 経由で IronOcr.Android パッケージをインストールします。IronTesseract クラスを使用して画像を処理し、テキストを抽出します。プロジェクトが適切に Android をターゲットとするよう、.csproj ファイルを変更してください。

IronOcr.Android パッケージの目的は何ですか?

IronOcr.Android パッケージは、.NET MAUI プロジェクト内で Android デバイスに OCR 機能を提供するために特別に設計されています。Android をターゲットとするクロスプラットフォームアプリケーションでのテキスト認識機能の統合を簡素化します。

.NET MAUI プロジェクトを Android OCR に構成するにはどうすればよいですか?

.NET MAUI プロジェクトを、NuGet を通じて IronOcr.Android パッケージをインストールして構成します。新しい ItemGroup 要素を作成し、その中に IronOcr.Android の PackageReference を移動することにより、.csproj ファイルを Android にターゲットするよう調整します。これにより他のプラットフォームでのビルド問題を回避します。

OCR 設定のために MainActivity.cs にどのような変更が必要ですか?

Platforms -> Android の下の MainActivity.cs ファイルで、MainActivity メソッドを追加し、IronTesseract の Initialize メソッドを呼び出します。これにより、画像からテキストを処理するために必要な OCR 機能がセットアップされます。

OCR 機能を組み込むために MainPage.xaml をどのように編集できますか?

MainPage.xaml を編集してファイルをインポートするためのボタンと OCR の結果を表示するラベルを含めます。OCR 処理ロジックとユーザー入力を効果的に管理するために必要な UI 要素を定義します。

OCR 処理中にエラーが発生した場合、どうすればよいですか?

try-catch ブロックを使用して OCR 処理コードを囲み、例外を処理します。Debug.WriteLine または他のログ記録メカニズムを使用してエラーを記録し、問題の診断と修正に役立てます。

IronOcr.Android パッケージを Avalonia プロジェクトで使用することは可能ですか?

はい、IronOcr.Android パッケージは .NET MAUI と同様の設定プロセスで Avalonia プロジェクトでも使用できます。OCR 機能を有効にするためにプロジェクトの構成を適切に調整してください。

.NET MAUI を使用した Android OCR の完全なサンプルプロジェクトはどこで見つかりますか?

.NET MAUI で IronOCR ライブラリを使用した Android OCR の完全なサンプルプロジェクトは、ガイドに記載されているリンクからダウンロード可能です。このプロジェクトは、Visual Studio で開く準備が整った ZIP ファイルとして提供されます。

マルチプラットフォームプロジェクトで IronOcr.Android パッケージが Android のみをターゲットとすることをどのように確保しますか?

IronOcr.Android パッケージが Android のみをターゲットとするようにするには、.csproj ファイルを修正し、Android 用の条件付き ItemGroup を作成し、その中に IronOcr.Android の PackageReference を移動します。他のプラットフォーム用にビルドする際の競合を防ぎます。

カーティス・チャウ
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。

準備はできましたか?
Nuget ダウンロード 5,167,857 | Version: 2025.11 リリース