How to Read Text From Image in Blazor
Blazorフレームワークは、ASP.NETチームによって構築され、JavaScriptの代わりにHTMLとC#を使用してインタラクティブなUIウェブアプリケーションを開発するために使用されます。 BlazorはWebAssemblyを使用してウェブブラウザで直接C#コードを実行します。 これにより、ロジックを備えたコンポーネントを簡単に構築・開発し、繰り返し再利用することができます。 これは、C#でUIを構築するための開発者の間で人気のあるフレームワークです。
この記事では、IronOCRを使用して画像ファイルからテキストを読み取るためのBlazorサーバーアプリを作成します。
Blazorで光学文字認識を使用して画像からテキストを読み取るには?
前提条件
- 最新バージョンのVisual Studioを用意してください。 このリンクからダウンロードできます。
- ASP.NETとWeb開発のワークロード。 Visual Studioをインストールする際、このプロジェクトに必要なため、ASP.NETとWeb開発のワークロードを選択してインストールしてください。
- IronOCR C#ライブラリ。 画像データを機械が読み取れるテキストに変換するために、IronOCRを使用します。 IronOCRパッケージの.DLLファイルをIronのウェブサイトから直接ダウンロードするか、NuGetのウェブサイトからダウンロードできます。 IronOCRをダウンロードしてインストールするより便利な方法は、Visual StudioのNuGetパッケージマネージャーからです。
Blazorサーバーアプリを作成する
Visual Studioを開き、Blazorサーバーアプリを作成するための手順に従ってください:
-
新しいプロジェクトを作成をクリックし、リストされたプロジェクトテンプレートから"Blazorサーバーアプリ"を選択します。
Visual Studioでの新しいBlazorサーバーアプリの作成 -
次に、プロジェクトに適切な名前を付けます。 ここでは、それをBlazorReadTextと命名しています。
Blazorプロジェクトの構成 -
最後に、追加情報を設定し、作成をクリックします。
長期サポート.NETフレームワークとプロジェクトの追加情報の選択
これでBlazorサーバーアプリが作成されました。 次に、画像データをIronOCRで抽出する前に必要なパッケージをインストールする必要があります。
必要なパッケージの追加
BlazorInputFile
最初のステップはBlazorInputFileパッケージをインストールすることです。 これはBlazorアプリケーション用のコンポーネントで、サーバーに単一または複数のファイルをアップロードするのに使用されます。 このコンポーネントはBlazorアプリケーションのRazorページ上で画像ファイルをアップロードするために使用されます。 ソリューションのNuGetパッケージを管理を開いてBlazorInputFileを探します。
BlazorInputFileパッケージをインストール
プロジェクトのチェックボックスを選択し、インストールをクリックします。
次に、Pagesフォルダ内の_Host.cshtmlファイルを開き、以下 for JavaScriptファイルを追加します。
<script src="_content/BlazorInputFile/inputfile.js"></script>
ソリューションエクスプローラーから_Host.cshtmlファイルに移動
最後に、_Imports.razorファイルに次のコードを追加します。
@using BlazorInputFile'INSTANT VB TODO TASK: The following line uses invalid syntax:
'@using BlazorInputFile'INSTANT VB TODO TASK: The following line uses invalid syntax:
'@using BlazorInputFileIronOCR
IronOCRは様々な形式の画像をスキャンし、読み取るためのC#ライブラリです。 これは125以上の世界各国の言語で画像を操作する機能を提供します。
IronOCRをインストールするには、そのNuGetパッケージマネージャーを開き、IronOCRを検索します。 プロジェクトを選択し、インストールボタンをクリックします。
NuGetパッケージマネージャーでIronOCRパッケージをインストールする
_Imports.razorファイルにIronOCR名前空間を追加します。
@using IronOCR@using IronOCR'INSTANT VB TODO TASK: The following line uses invalid syntax:
'@using IronOCR'INSTANT VB TODO TASK: The following line uses invalid syntax:
'@using IronOCRBlazor UIコンポーネントの作成
コンポーネントは動的な振る舞いを示すためのビジネスロジックを持ったユーザーインターフェースを表現します。 BlazorはRazorコンポーネントを使用してアプリを構築します。これらのコンポーネントはネスト、再利用、プロジェクト間で共有することができます。 デフォルトで、アプリケーションにはFetchDataページが提供されています。 簡潔にするためにそれらを削除します。
BlazorReadTextアプリケーションの下のpagesフォルダを右クリックして、追加 > Razorコンポーネントを選択します。 Razorコンポーネントが見つからない場合は、新しいアイテムをクリックし、C#コンポーネントから"Razorコンポーネント"を選択します。 コンポーネントに"OCR.razor"という名前を付け、追加をクリックします。
新しいRazorコンポーネントの追加
ベストプラクティスは、このRazorページのコードを別のクラスに分けることです。 再度、ページフォルダを右クリックし、追加 > クラスを選択します。 このクラスにはページと同じ名前を付けて、追加をクリックします。 Blazorは賢いフレームワークで、このクラスを名前が同じページにタグ付けします。
OCR.razor.csコードファイルを作成
では、実際のコードの実装に進み、IronOCRを使用して画像データを読み取ります。
画像データを読み取るためのBlazor OCR.razor UIコンポーネントのソースコード
画像内のテキストを認識するには、画像をアップロードし、それをバイナリデータに変換してから、IronOCRメソッドを適用してテキストを抽出します。
OCR.razor.csクラスを開いて、次の例のソースコードを書きます。
using BlazorInputFile;
using Microsoft.AspNetCore.Components;
using IronOcr;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace BlazorReadText.Pages
{
public class OCRModel : ComponentBase
{
// Holds the extracted text from the image
protected string imageText;
// Holds the base64 string preview of the image
protected string imagePreview;
// Byte array to store uploaded image data
private byte[] imageFileBytes;
// Default status message for file upload
const string DefaultStatus = "Maximum size allowed for the image is 4 MB";
protected string status = DefaultStatus;
// Maximum file size allowed (4MB)
const int MaxFileSize = 4 * 1024 * 1024;
// Method to handle image preview and size/type validation
protected async Task ViewImage(IFileListEntry[] files)
{
var file = files.FirstOrDefault();
if (file == null)
{
return;
}
if (file.Size > MaxFileSize)
{
status = $"The file size is {file.Size} bytes, which exceeds the allowed limit of {MaxFileSize} bytes.";
return;
}
if (!file.Type.Contains("image"))
{
status = "Please upload a valid image file.";
return;
}
using (var memoryStream = new MemoryStream())
{
await file.Data.CopyToAsync(memoryStream);
imageFileBytes = memoryStream.ToArray();
string base64String = Convert.ToBase64String(imageFileBytes, 0, imageFileBytes.Length);
imagePreview = $"data:image/png;base64,{base64String}";
status = DefaultStatus;
}
}
// Method to extract text from the uploaded image using IronOCR
protected private async Task GetText()
{
if (imageFileBytes != null)
{
using (var ocr = new IronTesseract())
using (var input = new OcrInput(imageFileBytes))
{
OcrResult result = ocr.Read(input);
imageText = result.Text;
}
}
}
}
}using BlazorInputFile;
using Microsoft.AspNetCore.Components;
using IronOcr;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace BlazorReadText.Pages
{
public class OCRModel : ComponentBase
{
// Holds the extracted text from the image
protected string imageText;
// Holds the base64 string preview of the image
protected string imagePreview;
// Byte array to store uploaded image data
private byte[] imageFileBytes;
// Default status message for file upload
const string DefaultStatus = "Maximum size allowed for the image is 4 MB";
protected string status = DefaultStatus;
// Maximum file size allowed (4MB)
const int MaxFileSize = 4 * 1024 * 1024;
// Method to handle image preview and size/type validation
protected async Task ViewImage(IFileListEntry[] files)
{
var file = files.FirstOrDefault();
if (file == null)
{
return;
}
if (file.Size > MaxFileSize)
{
status = $"The file size is {file.Size} bytes, which exceeds the allowed limit of {MaxFileSize} bytes.";
return;
}
if (!file.Type.Contains("image"))
{
status = "Please upload a valid image file.";
return;
}
using (var memoryStream = new MemoryStream())
{
await file.Data.CopyToAsync(memoryStream);
imageFileBytes = memoryStream.ToArray();
string base64String = Convert.ToBase64String(imageFileBytes, 0, imageFileBytes.Length);
imagePreview = $"data:image/png;base64,{base64String}";
status = DefaultStatus;
}
}
// Method to extract text from the uploaded image using IronOCR
protected private async Task GetText()
{
if (imageFileBytes != null)
{
using (var ocr = new IronTesseract())
using (var input = new OcrInput(imageFileBytes))
{
OcrResult result = ocr.Read(input);
imageText = result.Text;
}
}
}
}
}Imports BlazorInputFile
Imports Microsoft.AspNetCore.Components
Imports IronOcr
Imports System.IO
Imports System.Linq
Imports System.Threading.Tasks
Namespace BlazorReadText.Pages
Public Class OCRModel
Inherits ComponentBase
' Holds the extracted text from the image
Protected imageText As String
' Holds the base64 string preview of the image
Protected imagePreview As String
' Byte array to store uploaded image data
Private imageFileBytes As Byte()
' Default status message for file upload
Const DefaultStatus As String = "Maximum size allowed for the image is 4 MB"
Protected status As String = DefaultStatus
' Maximum file size allowed (4MB)
Const MaxFileSize As Integer = 4 * 1024 * 1024
' Method to handle image preview and size/type validation
Protected Async Function ViewImage(files As IFileListEntry()) As Task
Dim file = files.FirstOrDefault()
If file Is Nothing Then
Return
End If
If file.Size > MaxFileSize Then
status = $"The file size is {file.Size} bytes, which exceeds the allowed limit of {MaxFileSize} bytes."
Return
End If
If Not file.Type.Contains("image") Then
status = "Please upload a valid image file."
Return
End If
Using memoryStream = New MemoryStream()
Await file.Data.CopyToAsync(memoryStream)
imageFileBytes = memoryStream.ToArray()
Dim base64String As String = Convert.ToBase64String(imageFileBytes, 0, imageFileBytes.Length)
imagePreview = $"data:image/png;base64,{base64String}"
status = DefaultStatus
End Using
End Function
' Method to extract text from the uploaded image using IronOCR
Protected Private Async Function GetText() As Task
If imageFileBytes IsNot Nothing Then
Using ocr = New IronTesseract()
Using input = New OcrInput(imageFileBytes)
Dim result As OcrResult = ocr.Read(input)
imageText = result.Text
End Using
End Using
End If
End Function
End Class
End NamespaceImports BlazorInputFile
Imports Microsoft.AspNetCore.Components
Imports IronOcr
Imports System.IO
Imports System.Linq
Imports System.Threading.Tasks
Namespace BlazorReadText.Pages
Public Class OCRModel
Inherits ComponentBase
' Holds the extracted text from the image
Protected imageText As String
' Holds the base64 string preview of the image
Protected imagePreview As String
' Byte array to store uploaded image data
Private imageFileBytes As Byte()
' Default status message for file upload
Const DefaultStatus As String = "Maximum size allowed for the image is 4 MB"
Protected status As String = DefaultStatus
' Maximum file size allowed (4MB)
Const MaxFileSize As Integer = 4 * 1024 * 1024
' Method to handle image preview and size/type validation
Protected Async Function ViewImage(files As IFileListEntry()) As Task
Dim file = files.FirstOrDefault()
If file Is Nothing Then
Return
End If
If file.Size > MaxFileSize Then
status = $"The file size is {file.Size} bytes, which exceeds the allowed limit of {MaxFileSize} bytes."
Return
End If
If Not file.Type.Contains("image") Then
status = "Please upload a valid image file."
Return
End If
Using memoryStream = New MemoryStream()
Await file.Data.CopyToAsync(memoryStream)
imageFileBytes = memoryStream.ToArray()
Dim base64String As String = Convert.ToBase64String(imageFileBytes, 0, imageFileBytes.Length)
imagePreview = $"data:image/png;base64,{base64String}"
status = DefaultStatus
End Using
End Function
' Method to extract text from the uploaded image using IronOCR
Protected Private Async Function GetText() As Task
If imageFileBytes IsNot Nothing Then
Using ocr = New IronTesseract()
Using input = New OcrInput(imageFileBytes)
Dim result As OcrResult = ocr.Read(input)
imageText = result.Text
End Using
End Using
End If
End Function
End Class
End Namespace上記のコードでは:
ViewImageメソッドはアップロードされた画像ファイルを処理するために使用されます。ファイルが画像であるかどうかを検証し、サイズが指定された制限を満たしているかを確認します。 ファイルサイズやファイルタイプにおけるエラーが発生した場合、if-elseブロックを使用して処理されます。 その後、画像はIronOcr.OcrInputは画像をバイナリ形式で受け入れることができます。GetTextメソッドはIronOCRを使用して入力イメージからテキストを抽出します。 IronOCRはTesseract 5エンジンを採用し、125以上の言語をサポートしています。
抽出されたテキストは表示のためにimageText変数に格納されます。 ライブラリは追加の設定なしで英語のテキスト画像をサポートしています。 このコード例ページ上で様々な言語の使用についての詳細を学ぶことができます。
BlazorフロントエンドUIコンポーネントのソースコード
次に、アプリケーションのUIを作成します。 OCR.razorファイルを開いて、次のコードを書きます。
@page "/IronOCR"
@inherits OCRModel
<h2>Optical Character Recognition (OCR) Using Blazor and IronOCR Software</h2>
<div class="row">
<div class="col-md-5">
<textarea disabled class="form-control" rows="10" cols="15">@imageText</textarea>
</div>
<div class="col-md-5">
<div class="image-container">
<img class="preview-image" width="800" height="500" src=@imagePreview>
</div>
<BlazorInputFile.InputFile OnChange="@ViewImage" />
<p>@status</p>
<hr />
<button class="btn btn-primary btn-lg" @onclick="GetText">
Extract Text
</button>
</div>
</div>
上記のコードにおいて、UIには以下が含まれます:
- 画像ファイルを選択するための入力ファイルタグ。
- 画像を表示するための画像タグ。
GetTextメソッドを起動するボタン。- 画像データから抽出されたテキストを表示するためのテキストエリア。
ナビゲーションメニューへのリンクの追加
最後に、OCR.razorページへのリンクをSharedフォルダに追加します。
<div class="nav-item px-3">
<NavLink class="nav-link" href="IronOCR">
<span class="oi oi-plus" aria-hidden="true"></span> Read Image Text
</NavLink>
</div>
FetchDataへのリンクは不要なので削除します。
これで全て完了し、使用する準備が整いました。 F5を押してアプリケーションを実行します。
フロントエンドは以下のように表示されるはずです:
BlazorサーバーアプリのUI
画像をアップロードし、出力を視覚化するためにテキストを抽出しましょう。
アップロードされた画像と抽出されたテキスト
出力されたテキストはきれいで、テキストエリアからコピーすることができます。
まとめ
この記事では、Blazorサーバーアプリケーションで背後にコードがあるBlazor UIコンポーネントを作成し、画像からテキストを読み取る方法を示しました。 IronOCRは、あらゆるC#ベースのアプリケーションでテキストを抽出するための多様なライブラリです。 最新 for .NETフレームワークをサポートし、Razorアプリケーションともうまく連携できます。 IronOCRはWindows、Linux、macOS、Docker、Azure、AWS、およびMAUIでサポートされているクロスプラットフォームライブラリです。 また、IronOCRは、Tesseractからのベストな結果を用いて高精度を提供し、追加の設定を必要としません。 マルチページフレームの TIFF 、 PDF ファイル、およびすべての一般的な画像形式をサポートします。 画像からバーコードの値を読み取ることも可能です。
また、無料トライアルでIronOCRを無料で試すことができます。 ソフトウェアライブラリはここからダウンロードできます。
関連する記事
