跳過到頁腳內容
使用 IRONOCR

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

Blazor 框架由 ASP.NET 團隊構建,用於使用 HTML 和 C# 而不是 JavaScript 開發互動式 UI Web 應用程式。 Blazor 使用 WebAssembly 直接在 Web 瀏覽器中執行 C# 程式碼。 這樣就可以輕鬆地建構和開發具有邏輯的元件,並重複使用它們。 它是開發者在 C# 中建立使用者介面時常用的框架。

在本文中,我們將建立一個 Blazor Server 應用程序,用於使用 IronOCR 和光學字元辨識 (OCR) 從影像檔案中讀取文字。

如何在 Blazor 中使用光學字元辨識技術從影像中讀取文字?

先決條件

  1. 擁有最新版本的 Visual Studio。 你可以透過這個連結下載。
  2. ASP.NET 和 Web 開發工作量。 安裝 Visual Studio 時,請選擇 ASP.NET 和 Web 開發工作負載進行安裝,因為本專案需要這些元件。
  3. IronOCR C# 庫。 我們將使用 IronOCR 將圖像資料轉換為機器可讀文字。 您可以直接從Iron 網站下載 IronOCR 套件 .DLL 文件,也可以從NuGet 網站下載。 更方便的下載和安裝 IronOCR 的方式是透過 Visual Studio 中的 NuGet 套件管理器。

建立 Blazor 伺服器應用程式

開啟 Visual Studio,請依照下列步驟建立 Blazor 伺服器應用程式:

  1. 點選建立新項目,然後從列出的項目範本中選擇" Blazor Server App "。

    如何在 Blazor 中從圖像中讀取文本,圖 1:在 Visual Studio 中建立一個新的 Blazor 伺服器應用程式 在 Visual Studio 中建立一個新的 Blazor Server 應用程式

  2. 接下來,為你的專案取個合適的名字。 這裡,我們將其命名為BlazorReadText

    如何在 Blazor 中從圖像中讀取文本,圖 2:配置 Blazor 項目 配置 Blazor 項目

  3. 最後,設定附加資訊並點選"建立"。

    如何在 Blazor 中從圖像中讀取文本,圖 3:選擇長期支援 .NET Framework 以及專案的其他信息 選擇長期支援的 .NET Framework 以及專案的其他信息

Blazor 伺服器應用程式已建立完成。 現在我們需要安裝必要的軟體包,然後才能使用 IronOCR 提取影像資料。

加入必要的軟體包

BlazorInputFile

第一步是安裝BlazorInputFile套件。 它是 Blazor 應用程式的一個元件,用於將單一或多個檔案上傳到伺服器。 該元件將用於在 Blazor 應用程式的 Razor 頁面上上傳圖像檔案。 開啟"管理解決方案的 NuGet 套件" ,然後瀏覽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:從解決方案資源管理器導航到 _Host.cshtml 文件 從解決方案資源管理器導覽至_Host.cshtml檔案。

最後,在_Imports.razor檔案中加入以下程式碼。

@using BlazorInputFile
@using BlazorInputFile
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'@using BlazorInputFile
$vbLabelText   $csharpLabel

IronOCR。

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

若要安裝 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
$vbLabelText   $csharpLabel

建立 Blazor UI 元件

元件代表使用者介面,並包含用於展現動態行為的業務邏輯。 Blazor 使用 Razor 元件來建立應用程式。這些元件可以嵌套、重複使用,並在項目之間共用。 預設情況下,應用程式中會提供Counter頁面和FetchData頁面; 為了簡化起見,省略了這些內容。

右鍵單擊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;
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
		Private Const DefaultStatus As String = "Maximum size allowed for the image is 4 MB"
		Protected status As String = DefaultStatus

		' Maximum file size allowed (4MB)
		Private Const MaxFileSize As Integer = 4 * 1024 * 1024

		' Method to handle image preview and size/type validation
		Protected Async Function ViewImage(ByVal 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 As 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
		Private Protected 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
$vbLabelText   $csharpLabel

在上述程式碼中

ViewImage方法用於處理上傳的映像檔。它會驗證檔案是否為影像,並檢查檔案大小是否符合指定的限制。 如果檔案大小或檔案類型出現任何錯誤,則使用if-else區塊進行處理。 然後將圖像複製到MemoryStream並轉換為位元組數組,因為IronOcr.OcrInput可以接受二進位格式的圖像。

  • GetText方法利用 IronOCR 從輸入影像中擷取文字。 IronOCR採用Tesseract 5引擎,支援125多種語言。

提取出的文字儲存在imageText變數中以供顯示。 該庫無需額外配置即可支援英文文字圖像。 您可以在此程式碼範例頁面上了解更多關於使用不同語言的資訊。

Blazor前端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>

上面的程式碼中包含以下使用者介面:

  • 用於選擇影像檔案的輸入檔標籤。
  • 用於顯示影像的影像標籤。
  • 一個觸發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 伺服器應用程式的使用者介面 Blazor 伺服器應用程式的使用者介面

讓我們上傳一張圖片,提取其中的文本,並將結果視覺化。

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

輸出文字清晰,可以從文字區域複製。

摘要

本文示範如何在 Blazor 伺服器應用程式中建立具有背景程式碼的 Blazor UI 元件,以從圖像中讀取文字。 IronOCR 是一個功能強大的庫,可用於在任何基於 C# 的應用程式中提取文字。 它支援最新的 .NET Framework,並且可以很好地與 Razor 應用程式一起使用。 IronOCR 是一個跨平台庫,支援 Windows、Linux、macOS、 Docker 、Azure、AWS 和MAUI 。 此外,IronOCR 利用 Tesseract 的最佳結果提供高精度,無需任何額外設定。 它支援多頁框架 TIFFPDF 文件以及所有流行的圖像格式。 也可以從影像中讀取條碼值

您也可以免費試用 IronOCR。 從這裡下載軟體庫。

常見問題解答

我該如何在Blazor伺服器應用程式中從圖片讀取文字?

您可以使用 IronOCR 從 Blazor Server App 中的圖像讀取文字。首先,使用 BlazorInputFile 套件上傳圖片,然後在 IronOCR 中使用 GetText 方法從圖片中擷取文字。

設定OCR的Blazor伺服器應用程式需要哪些步驟?

若要為 OCR 設定 Blazor 伺服器應用程式,請確保您擁有具備 ASP.NET 與 Web 開發工作負載的 Visual Studio。然後,建立新的 Blazor Server App,並透過 NuGet 套件管理員安裝 IronOCR。

如何在 Blazor 應用程式中處理檔案上傳?

Blazor 應用程式中的檔案上傳可以使用 BlazorInputFile 套件來管理。此套件允許上傳單一或多個檔案,這對於處理 OCR 的影像非常重要。

IronOCR 在文字擷取方面可以支援多國語言嗎?

是的,IronOCR 支援多種語言的文字擷取。它使用 Tesseract 5 引擎,能夠高準確度地從影像中識別各種語言的文字。

在跨平台應用程式中使用 IronOCR 有哪些優點?

IronOCR 為跨平台應用程式提供多項優勢,包括相容於 Windows、Linux、macOS、Docker、Azure、AWS 和 MAUI。這使其成為多樣化環境中 OCR 的多用途選擇。

如何在 Blazor 元件中使用 IronOCR 從影像中擷取文字?

在 Blazor 元件中,您可以從圖片中擷取文字,方法是先上傳圖片檔案,再使用 OCR.razor.cs 類呼叫 IronOCR 的 GetText 方法,處理圖片並擷取文字。

OCR 功能的 Blazor UI 有哪些關鍵元件?

用於 OCR 功能的 Blazor UI 包括一個用於選擇影像的輸入檔案標籤、一個用於預覽的影像標籤、一個用於觸發 OCR 程序的按鈕,以及一個用於顯示擷取文字的文字區域。

如何在 Blazor 應用程式中導覽至 OCR 頁面?

若要在 Blazor 應用程式中導航至 OCR 頁面,請在 Shared 資料夾下的 NavMenu.razor 檔案中加入導航項目。包含一個指向 OCR 頁面的 NavLink

Kannaopat Udonpant
軟體工程師
在成為软件工程師之前,Kannapat 從日本北海道大學完成了環境資源博士學位。在追逐學位期间,Kannapat 還成為了生產工程系一部份——汽車机器人实验室的成員。2022 年,他利用他的 C# 技能加入 Iron Software 的工程團隊, 專注於 IronPDF。Kannapat 珍惜他的工作,因为他直接向编写大部分 IronPDF 使用的代码的开发者学习。除了同行学习,Kannapat 还喜欢在 Iron Software 工作的社交十环。当他不编写代码或文档时,Kannapat 通常在他的 PS5 上打游戏或重看《The Last of Us》。