在图像上执行 Optical Character Recognition (OCR) 是一项复杂的任务。本主题逐步说明如何在 C# 中快速轻松地从图像中提取文本。通过使用 Aspose.OCR for .NET,您可以通过几个步骤在 C# 中简单地从图像中读取字符。
在 C# 中从图像中提取文本的步骤
- 使用 Aspose.OCR for .NET NuGet 包
- 首先包含 Aspose.OCR namespace 引用
- 使用 SetLicense 方法申请 Aspose 许可证
- 创建 AsposeOcr Class 实例的对象
- 通过应用 OCR 使用 RecognizeImage 方法从图像中提取文本
- 使用 FileStream 和 StreamWriter 类将提取的文本保存到文本文件
上面的步骤向您展示了在 C# 中从图像中读取字符非常容易。上述步骤的代码如下所示。
在 C# 中从图像中提取文本的代码
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
//Add Aspose.OCR for .NET package reference | |
//Use following namespaces to Extract Text from Image | |
using Aspose.OCR; | |
namespace ExtractTextFromImage | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
//Set Aspose license before extracting text from image | |
//using Aspose.OCR for .NET | |
Aspose.OCR.License AsposeOCRLicense = new Aspose.OCR.License(); | |
AsposeOCRLicense.SetLicense(@"c:\asposelicense\license.lic"); | |
//Create an instance of AsposeOcr class before you can apply | |
//OCR on an image to extract the text from it | |
AsposeOcr ExtractTextFromImage = new AsposeOcr(); | |
//Read image using RecognizeImage method on which OCR need to be applied for text extraction | |
string TextExtractedFromImage = ExtractTextFromImage.RecognizeImage("ExampleOCRImageToExtractText.jpg"); | |
//Save extracted text to a text file using File Stream and StreamWriter | |
//classes of System.IO | |
FileStream FStream = new FileStream("ExtractTextFromImageUsingOCR.txt", FileMode.Create); | |
StreamWriter SWriter = new StreamWriter(FStream); | |
//Write extracted text to the file | |
SWriter.WriteLine(TextExtractedFromImage); | |
SWriter.Flush(); | |
//Close FileStream and StreamWriter bojects | |
SWriter.Close(); | |
FStream.Close(); | |
} | |
} | |
} |
如果您使用 C# 语言,则该方法对于任何类型的 .NET 应用程序都是相同的。无论您是想从图像中提取所有文本,还是从图像中逐行读取文本,Aspose.OCR for .NET 都可以帮助您做到这一点。