如何在 Blazor 中从图像中读取文本
Blazor 框架由 ASP.NET 团队构建,用于开发使用 HTML 和 C# 而不是 JavaScript 的交互式 UI Web 应用程序。 Blazor 使用 WebAssembly 在网页浏览器中直接运行 C# 代码。 这使得构建和开发具有逻辑性的组件以及重复使用这些组件变得非常容易。 它是开发人员常用的框架,用于用 C# 构建用户界面。
在本文中,我们将使用 IronOCR 创建一个 Blazor Server 应用程序,用于使用光学字符识别(OCR)从图像文件中读取文本。
如何使用 Blazor 中的光学字符识别从图像中读取文本?
前提条件
1.拥有最新版本的 Visual Studio。 您可以从链接下载。 2.ASP.NET 和 Web 开发工作量。 安装Visual Studio时,选择ASP.NET和Web开发工作负载进行安装,因为它是此项目所需的。
- IronOCR C#库. 我们将使用 IronOCR 将图像数据转换为机器可读文本。 您可以直接从Iron网站下载IronOCR包的.DLL文件,或从NuGet网站下载它。 下载并安装IronOCR的更便捷方式是在Visual Studio中的NuGet包管理器。
创建 Blazor 服务器应用程序
打开Visual Studio并按照步骤创建Blazor Server应用程序:
- 点击创建新项目,然后从列出的项目模板中选择"Blazor Server App"。
在 Visual Studio 中创建新的 Blazor 服务器应用程序
2.接下来,为您的项目取一个恰当的名称。 在此,我们将其命名为 BlazorReadText。
配置 Blazor 项目
3.最后,设置附加信息并单击创建。
选择长期支持 .NET Framework 和项目的其他信息
Blazor 服务器应用程序现已创建。 现在,在使用 IronOCR 提取图像数据之前,我们需要安装必要的软件包。
添加必要的包
BlazorInputFile
第一步是安装BlazorInputFile包。 它是 Blazor 应用程序的一个组件,用于将单个或多个文件上传到服务器。 该组件将用于在 Blazor 应用程序中的 Razor 页面上传图片文件。 打开解决方案的NuGet包管理并搜索BlazorInputFile。
安装BlazorInputFile包
选择项目的复选框,然后单击安装。
现在,打开Pages文件夹中的_Host.cshtml文件,并添加以下JavaScript文件:
<script src="_content/BlazorInputFile/inputfile.js"></script>
<script src="_content/BlazorInputFile/inputfile.js"></script>
从解决方案资源管理器导航到_Host.cshtml文件
最后,将以下代码添加到_Imports.razor文件中。
@using BlazorInputFile
@using BlazorInputFile
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'@using BlazorInputFile
IronOCR
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
创建 Blazor UI 组件
一个组件代表一个具有业务逻辑的用户界面,以展示动态行为。 Blazor 使用 Razor 组件来构建应用程序。这些组件可以嵌套、重复使用并在项目间共享。 默认情况下,应用程序中提供FetchData页面; 去掉那些简单的词语。
右键单击BlazorReadText应用下的pages文件夹,然后选择添加 > Razor组件。 如果找不到 Razor Component,请点击 新建项目,然后从 C# 组件中选择 "Razor Component"。 将组件命名为 "OCR.razor",然后单击 "添加"。
添加新的Razor组件
最佳做法是将该剃刀页面的代码与其他类分开。 再次右键单击页面文件夹,选择 Add > Class。 将该类命名为与页面名称相同的名称,然后单击添加。 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
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
在上述代码中
ViewImage方法用于处理上传的图像文件。它验证文件是否为图像并检查大小是否符合指定的限制。 如果在文件大小或文件类型上发生任何错误,它将通过if-else块进行处理。 然后将图像复制到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文件夹下的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>
移除链接到FetchData的链接,因为它们不需要。
现在一切都已完成,随时可以使用。 按 F5 运行应用程序。
前台应如下所示:
Blazor Server应用程序的UI
让我们上传一张图片并提取文本,以直观地显示输出结果。
上传的图像和提取的文本
输出文本要干净整洁,可以从文本区复制。
摘要
本文演示了如何在 Blazor 服务器应用程序中创建一个 Blazor UI Component,并在其背后添加代码,以便从图像中读取文本。 IronOCR 是一个多功能库,可在任何基于 C# 的应用程序中提取文本。 它支持最新的 .NET Framework,可以很好地与 Razor 应用程序配合使用。 IronOCR 是一个跨平台库,支持 Windows、Linux、macOS、Docker、Azure、AWS 和 MAUI。 此外,IronOCR 使用 Tesseract 的最佳结果提供高准确性,无需任何额外设置。 它支持 多页框架 TIFF、PDF 文件 和所有流行的图像格式。 还可以从图像中读取条形码值。
您还可以在免费试用版中免费试用 IronOCR。 从此处下载软件库。
常见问题解答
如何在Blazor服务器应用程序中从图像中读取文本?
您可以使用IronOCR在Blazor服务器应用程序中从图像中读取文本。首先,使用BlazorInputFile包上传图像,然后在IronOCR中使用GetText方法从图像中提取文本。
设置Blazor服务器应用程序以实现OCR需要哪些步骤?
要设置一个用于OCR的Blazor服务器应用程序,确保您具备带有ASP.NET和Web开发工作负载的Visual Studio。然后,创建一个新的Blazor服务器应用程序并通过NuGet包管理器安装IronOCR。
如何在Blazor应用程序中处理文件上传?
可以使用BlazorInputFile包管理Blazor应用程序中的文件上传。该包允许上传单个或多个文件,这对于处理图像以实现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。



