使用 IRONOCR

如何在 Blazor 中從圖像讀取文本

已更新 2024年1月29日
分享:

Blazor 框架是由 ASP.NET 團隊構建的,用於使用 HTML 和 C# 而不是 JavaScript 開發互動 UI 網頁應用程式。Blazor 使用 WebAssembly 在網頁瀏覽器中直接執行 C# 代碼。這使得構建和開發具有邏輯的組件變得簡單,並且能夠重複利用它們。這是一個在開發者中使用 C# 構建 UI 的流行框架。

在本文中,我們將創建一個 Blazor Server 應用程式,用於使用光學字符識別讀取圖像文件中的文本。 (光學字符識別) 使用IronOCR

如何在Blazor中使用光學字符識別從圖像中讀取文本?

先決條件

  1. 安裝最新版本的 Visual Studio。您可以從這裡下載。 連結.

  2. ASP.NET 和 Web 開發工作負載。安裝 Visual Studio 時,選擇 ASP.NET 和 Web 開發工作負載進行安裝,因為這是此項目所必需的。

  3. IronOCR C# 函式庫我們將使用IronOCR將圖像數據轉換為機器可讀的文本。您可以直接從網站下載IronOCR套件的.DLL文件。 Iron Software網站 或者從下載它 NuGet網站在 Visual Studio 中從 NuGet 套件管理器下載並安裝 IronOCR 是一種更方便的方法。

建立 Blazor 伺服器應用程式

打開 Visual Studio 並按照以下步驟建立 Blazor 伺服器應用程式:

  1. 點擊創建新專案,然後從列出的專案模板中選擇 "Blazor 伺服器應用程式"

    如何在Blazor中從圖像讀取文字,圖1:在Visual Studio中創建一個新的Blazor Server應用程式

    在 Visual Studio 中创建一个新的 Blazor 服务器应用程序

接下来,为您的项目命名。这里,我们将其命名为 "BlazorReadText"

![如何在 Blazor 中讀取圖片文字,圖 2:配置 Blazor 項目](/static-assets/ocr/blog/read-text-from-image-blazor-tutorial/read-text-from-image-blazor-tutorial-2.webp)

**配置 Blazor 專案**
  1. 最後,設定附加資訊並點選建立。

    如何在 Blazor 中從圖像中讀取文本,圖 3:選擇長期支持的 .NET 框架以及項目的附加信息

    選擇長期支援的 .NET 框架以及項目額外資訊

Blazor Server App 現已建立。現在我們需要安裝必要的套件,然後使用 IronOCR 提取圖像數據。

添加必要的套件

BlazorInputFile

第一步是安裝 BlazorInputFile 套件。這是一個用於 Blazor 應用程式的元件,可用來上傳單一或多個檔案到伺服器。這個元件將用於在 Blazor 應用程式的 Razor 頁面上傳圖片檔案。打開 Manage NuGet Packages for Solutions,然後搜尋 BlazorInputFile

如何在 Blazor 中從圖片讀取文字,圖 4:安裝 BlazorInputFile 套件

安裝 BlazorInputFile 套件

選取專案的複選框並點擊安裝。

現在,打開 Pages 資料夾中的 _Host.cshtml 文件,並添加以下 JavaScript 文件:

 <script src="_content/BlazorInputFile/inputfile.js"></script>
 <script src="_content/BlazorInputFile/inputfile.js"></script>
HTML

如何在Blazor中從圖像中讀取文本,圖5:從Solution Explorer中導航至_Host.cshtml文件

導航到解決方案資源管理器中的 _Host.cshtml 文件

最後,在 _Imports.razor 文件中添加以下代碼。

@using BlazorInputFile
@using BlazorInputFile
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'@using BlazorInputFile
VB   C#

IronOCR

IronOCR 是一個 C# 程式庫,用於掃描和閱讀不同格式的圖像。它提供處理超過127種全球語言圖像的功能。

要安裝 IronOCR,請打開 NuGet 套件管理器並搜尋 IronOCR。選擇專案並點擊 安裝 按鈕。

如何在 Blazor 中從圖像中讀取文字,圖6:在 NuGet 包管理器中安裝 IronOCR 套件

在NuGet套件管理器中安裝IronOCR套件

_Imports.razor文件中添加IronOCR命名空間:

@using IronOCR
@using IronOCR
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'@using IronOCR
VB   C#

建立 Blazor UI 元件

元件代表具有業務邏輯的使用者介面,以展示動態行為。Blazor 使用 Razor 元件來構建其應用程式。這些元件可以嵌套、重複使用並在項目之間共享。預設情況下,應用程式中提供了 CounterFetchData 頁面,為簡化起見,可將其移除。

右鍵點擊 BlazorReadText 應用程式下的 pages 資料夾,然後選擇 新增 > Razor 元件。如果沒有找到 Razor 元件,請點擊 新增項目,並從 C# 元件中選擇 "Razor 元件"。將元件命名為 "OCR.razor" 並點擊新增。

如何在 Blazor 中從圖片中讀取文字,圖 7:新增 Razor 元件

新增 Razor 元件

一個最佳做法是將這個 Razor 頁面的代碼分離成另一個類。再次右鍵點擊頁面文件夾並選擇 新增 > 類別。將類別命名為與頁面名稱相同,然後點擊新增。Blazor 是一個智能框架,它會將此類別標記為與名稱相同的頁面。

如何在 Blazor 中從圖像讀取文本,圖 8:為 OCR.razor Razor 組件創建一個 OCR.razor.cs 代碼文件

OCR.razor Razor 元件建立一個 OCR.razor.cs 程式碼檔案

現在,讓我們進行實際的程式碼實作,將使用 IronOCR 來讀取影像數據。

Blazor OCR.razor UI 元件來源代碼讀取圖像數據

要識別圖像中的文字,請上傳圖像,將其轉換為二進制數據,然後應用 IronOCR 方法提取文字。

打開 OCR.razor.cs 類並寫入以下範例源代碼:


using BlazorInputFile;
using Microsoft.AspNetCore.Components;
using IronOcr;

namespace BlazorReadText.Pages
{
    public class OCRModel : ComponentBase
    {
        protected string imageText;
        protected string imagePreview;
        byte [] imageFileBytes;

        const string DefaultStatus = "Maximum size allowed for the image is 4 MB";
        protected string status = DefaultStatus;

        const int MaxFileSize = 4 * 1024 * 1024; // 4MB

        protected async Task ViewImage(IFileListEntry [] files)
        {
            var file = files.FirstOrDefault();
            if (file == null)
            {
                return;
            }
            else if (file.Size > MaxFileSize)
            {
                status = $"The file size is {file.Size} bytes, this is more than the allowed limit of {MaxFileSize} bytes.";
                return;
            }
            else if (!file.Type.Contains("image"))
            {
                status = "Please uplaod a valid image file";
                return;
            }
            else
            {
                var memoryStream = new MemoryStream();
                await file.Data.CopyToAsync(memoryStream);
                imageFileBytes = memoryStream.ToArray();
                string base64String = Convert.ToBase64String(imageFileBytes, 0, imageFileBytes.Length);

                imagePreview = string.Concat("data:image/png;base64,", base64String);
                memoryStream.Flush();
                status = DefaultStatus;
            }
        }

        protected private async Task GetText()
        {
            if (imageFileBytes != null)
            {
                IronTesseract ocr = new IronTesseract();
                using (OcrInput input = new OcrInput(imageFileBytes))
                {
                    OcrResult result = ocr.Read(input);
                    imageText = result.Text;
                }
            }
        }
    }
}

using BlazorInputFile;
using Microsoft.AspNetCore.Components;
using IronOcr;

namespace BlazorReadText.Pages
{
    public class OCRModel : ComponentBase
    {
        protected string imageText;
        protected string imagePreview;
        byte [] imageFileBytes;

        const string DefaultStatus = "Maximum size allowed for the image is 4 MB";
        protected string status = DefaultStatus;

        const int MaxFileSize = 4 * 1024 * 1024; // 4MB

        protected async Task ViewImage(IFileListEntry [] files)
        {
            var file = files.FirstOrDefault();
            if (file == null)
            {
                return;
            }
            else if (file.Size > MaxFileSize)
            {
                status = $"The file size is {file.Size} bytes, this is more than the allowed limit of {MaxFileSize} bytes.";
                return;
            }
            else if (!file.Type.Contains("image"))
            {
                status = "Please uplaod a valid image file";
                return;
            }
            else
            {
                var memoryStream = new MemoryStream();
                await file.Data.CopyToAsync(memoryStream);
                imageFileBytes = memoryStream.ToArray();
                string base64String = Convert.ToBase64String(imageFileBytes, 0, imageFileBytes.Length);

                imagePreview = string.Concat("data:image/png;base64,", base64String);
                memoryStream.Flush();
                status = DefaultStatus;
            }
        }

        protected private async Task GetText()
        {
            if (imageFileBytes != null)
            {
                IronTesseract ocr = new IronTesseract();
                using (OcrInput input = new OcrInput(imageFileBytes))
                {
                    OcrResult result = ocr.Read(input);
                    imageText = result.Text;
                }
            }
        }
    }
}
Imports BlazorInputFile
Imports Microsoft.AspNetCore.Components
Imports IronOcr

Namespace BlazorReadText.Pages
	Public Class OCRModel
		Inherits ComponentBase

		Protected imageText As String
		Protected imagePreview As String
		Private imageFileBytes() As Byte

		Private Const DefaultStatus As String = "Maximum size allowed for the image is 4 MB"
		Protected status As String = DefaultStatus

		Private Const MaxFileSize As Integer = 4 * 1024 * 1024 ' 4MB

		Protected Async Function ViewImage(ByVal files() As IFileListEntry) As Task
			Dim file = files.FirstOrDefault()
			If file Is Nothing Then
				Return
			ElseIf file.Size > MaxFileSize Then
				status = $"The file size is {file.Size} bytes, this is more than the allowed limit of {MaxFileSize} bytes."
				Return
			ElseIf Not file.Type.Contains("image") Then
				status = "Please uplaod a valid image file"
				Return
			Else
				Dim memoryStream As New MemoryStream()
				Await file.Data.CopyToAsync(memoryStream)
				imageFileBytes = memoryStream.ToArray()
				Dim base64String As String = Convert.ToBase64String(imageFileBytes, 0, imageFileBytes.Length)

				imagePreview = String.Concat("data:image/png;base64,", base64String)
				memoryStream.Flush()
				status = DefaultStatus
			End If
		End Function

		Private Protected Async Function GetText() As Task
			If imageFileBytes IsNot Nothing Then
				Dim ocr As New IronTesseract()
				Using input As New OcrInput(imageFileBytes)
					Dim result As OcrResult = ocr.Read(input)
					imageText = result.Text
				End Using
			End If
		End Function
	End Class
End Namespace
VB   C#

在上面的程式碼中,ViewImage 方法用於從輸入文件中獲取上傳的文件並檢查它是否為圖像且大小小於指定值。如果在文件大小或文件類型上發生任何錯誤,if-else 區塊將處理它。然後,圖像被複製到 MemoryStream。最後,圖像被轉換成字節陣列,因為 IronOcr.OcrInput 可以接受二進位格式的圖像。

GetText 方法使用 IronOCR 來 閱讀文本 從輸入圖像中。IronOCR 使用最新的 Tesseract 5 引擎,並支持127 多種語言。將轉換後的圖像傳遞為位元組陣列作為 OcrInput 並使用取得結果 IronTesseract 讀取 方法。IronOCR團隊開發的IronTesseract是Google Tesseract的擴展版本。更多信息請訪問 C# Tesseract OCR 範例最後,提取的文本會保存在 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>
@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>
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'@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>
VB   C#

在上面的程式碼中,UI包含一個輸入檔案標籤以選擇圖片檔案和一個圖片標籤以顯示圖片。輸入欄位下方有一個按鈕,用於觸發 GetText 方法。還有一個文本區域,用於顯示從圖像數據中提取的文本。

將連結加入導航選單

最後,在 Shared 資料夾中的 NavMenu.razor 檔案新增一個連結至 OCR.razor 頁面。

<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>
<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>
HTML

刪除 CounterFetchData 的鏈接,因為它們沒有必要。

一切都已完成並準備就緒。按 F5 鍵運行應用程式。

前端應顯示如下:

如何在 Blazor 中從圖像中讀取文本,圖 9:Blazor 服務器應用的 UI

Blazor 伺服器應用程式的 UI

讓我們上傳一張圖片並提取文本來可視化輸出。

如何在Blazor中從圖片讀取文字 圖10:上傳的圖片和提取的文本

上傳的圖像和提取的文本

輸出文本乾淨,可以從文本區域複製。

摘要

本文展示了如何在 Blazor 伺服器應用程式中創建一個具有後端代碼的 Blazor UI 元件來讀取圖像中的文字。IronOCR 是一個多功能的庫,可以在任何基於 C# 的應用程式中提取文字。它支持最新的 .NET Framework,並且可以很好地與 Razor 應用程式一起使用。IronOCR 是一個跨平台的庫,支持 Windows、Linux 和 macOS。 Docker, Azure, AWS,和 MAUI此外,IronOCR 使用最好的 Tesseract 結果提供高精確度,無需任何額外設定。它支援 多頁框架 TIFF, PDF 檔案,以及所有流行的圖像格式。也可以 從圖像中讀取條碼值您也可以嘗試 IronOCR for 免費試用下載軟體庫從 這裡.

< 上一頁
發票 OCR API(開發者教程)
下一個 >
OCR 收據數據提取(逐步教程)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 2,433,305 查看許可證 >