在今天的数字时代,从图像中提取文本的能力越来越重要,无论你是处理扫描文档、商业卡或任何其他形式的图形数据,能够有效地搜索和操纵这些信息,可以节省很多时间和精力。
** 真相来源:** 下面的代码和流量与本文结束时的合并(控制器端点, AsposeOcr
使用,以及JSON响应格式。
完整的例子
原則
- .NET 8(或 .Net 6+) SDK
- Visual Studio / VS 代码
- NuGet 接入
Aspose.OCR
- (可选) 如果您计划超过评估限制的Aspose许可文件
步骤1:创建 ASP.NET Core MVC 项目
dotnet new mvc -n ImageTextSearchApp -f net8.0
cd ImageTextSearchApp
# Add Aspose.OCR
dotnet add package Aspose.OCR
** 為什麼MVC?** 基因使用控制器(HomeController
) ,观点,和一个经典 Startup
一个简单而已知的文件上传模式 + 服务器侧 OCR。
步骤2:准备静态资产和上传文件夹
管理员写下下载 wwwroot/uploads
创建该文件夹并确保应用程序可以写到它。
mkdir -p wwwroot/uploads
我们还允许静态文件中间软件 Startup
以此为主。 wwwroot
树是正确的服务。
步骤3:添加控制器(上传 + OCR + 搜索)
创建 Controllers/HomeController.cs 并实施 Index
+ SearchText
此操作保存了上传的图像,执行OCR,搜索一个关键字(案例不敏感),并返回JSON。
using System;
using System.IO;
using System.Threading.Tasks;
using Aspose.Ocr;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace ImageTextSearchApp
{
public class HomeController : Controller
{
private readonly IWebHostEnvironment _environment;
public HomeController(IWebHostEnvironment environment)
{
_environment = environment;
}
[HttpGet]
public IActionResult Index()
{
return View();
}
[HttpPost]
[RequestSizeLimit(20_000_000)] // ~20MB max, adjust as needed
public async Task<IActionResult> SearchText(IFormFile imageFile, string searchKeyword)
{
if (imageFile == null || imageFile.Length == 0)
return BadRequest("Image file is required.");
if (string.IsNullOrWhiteSpace(searchKeyword))
return BadRequest("Search keyword is required.");
// Ensure uploads directory exists
var uploadsDir = Path.Combine(_environment.WebRootPath, "uploads");
Directory.CreateDirectory(uploadsDir);
// Sanitize filename and save
var safeName = Path.GetFileName(imageFile.FileName);
var filePath = Path.Combine(uploadsDir, safeName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await imageFile.CopyToAsync(stream);
}
// Perform OCR on the uploaded image
using (var ocrEngine = new AsposeOcr())
{
var extractedText = await ocrEngine.RecognizeImageAsync(filePath);
// Case-insensitive keyword check
var found = extractedText?.IndexOf(searchKeyword, StringComparison.OrdinalIgnoreCase) >= 0;
var searchResult = found ? "Keyword found!" : "Keyword not found.";
// Return minimal JSON (exact shape matches the gist)
return Json(new { extractedText, searchResult });
}
}
}
}
注意事項
- 我们添加了一个小文件大小限制和目录创建的强度。
- 编写文件类型(
.png/.jpg/.jpeg/.tif
)并考虑病毒扫描。
步骤4: Wire Up Startup 和 Program
创建 Startup.cs 和 Program.CS 的格式,以便允许 MVC、静态文件、路由和 HTTPS 重新引导。
首頁 > CS > STARTUP
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace ImageTextSearchApp
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles(); // serves wwwroot (including /uploads)
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
- 编程.cs *
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace ImageTextSearchApp
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
步骤5:构建上传 + 搜索UI(Razor View)
创建 Views/Home/Index.cshtml 使用简单的上传表格和搜索框。 /Home/SearchText
,打印 OCR 文本,并突出浏览器中的相匹配(不需要服务器更改)。
@{
ViewData["Title"] = "Image Text Search";
}
<h1 class="mb-3">Image Text Search (Aspose.OCR + ASP.NET Core)</h1>
<form id="ocrForm" enctype="multipart/form-data" class="mb-4">
<div class="form-group mb-2">
<label for="imageFile">Select image</label>
<input type="file" id="imageFile" name="imageFile" accept=".png,.jpg,.jpeg,.tif,.tiff,.bmp" class="form-control" required />
</div>
<div class="form-group mb-2">
<label for="searchKeyword">Keyword</label>
<input type="text" id="searchKeyword" name="searchKeyword" class="form-control" placeholder="Enter a word to find..." required />
</div>
<button type="submit" class="btn btn-primary">Upload & Search</button>
</form>
<div id="result" class="mt-3">
<h3>Result</h3>
<p id="searchStatus" class="fw-bold"></p>
<pre id="extractedText" style="white-space: pre-wrap"></pre>
</div>
@section Scripts {
<script>
(function () {
const form = document.getElementById('ocrForm');
const statusEl = document.getElementById('searchStatus');
const textEl = document.getElementById('extractedText');
function escapeHtml(s) {
return s.replace(/[&<>"']/g, c => ({
'&': '&', '<': '<', '>': '>', '"': '"', "'": '''
}[c]));
}
function highlight(text, keyword) {
if (!keyword) return escapeHtml(text);
const pattern = new RegExp(`(${keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
return escapeHtml(text).replace(pattern, '<mark>$1</mark>');
}
form.addEventListener('submit', async (e) => {
e.preventDefault();
statusEl.textContent = 'Processing...';
textEl.textContent = '';
const formData = new FormData(form);
try {
const res = await fetch('/Home/SearchText', {
method: 'POST',
body: formData
});
if (!res.ok) {
const msg = await res.text();
statusEl.textContent = `Error: ${msg}`;
return;
}
const data = await res.json();
statusEl.textContent = data.searchResult || '';
const kw = document.getElementById('searchKeyword').value;
textEl.innerHTML = highlight(data.extractedText || '', kw);
} catch (err) {
statusEl.textContent = 'Unexpected error. See console.';
console.error(err);
}
});
})();
</script>
}
这将实施 ** 实时突出在提取的文本** 区块。放置突出点 在图像上本身将需要 OCR 封锁盒子和绘图表面(不覆盖的)。
步骤6:运行应用程序
dotnet run
打开在控制台中显示的 URL(例如, https://localhost:5001
).上传图像,输入一个关键字,然后单击 上传和搜索。
Keyword found!
或Keyword not found.
(由服务器创建)- 与客户端侧的 ** 提取文本**
<mark>
突出
步骤7:生产准备考虑(可选)
- 文件验证:检查MIME类型/扩展,并考虑防病毒扫描。
- ** 尺寸限制**:使用
RequestSizeLimit
(显示) 和逆转 proxy/web.config 限制,如有必要。 - Cleanup:定期删除旧文件
wwwroot/uploads
. - 位置:如果您需要多种语言,则设置 OCR 语言选项服务器侧。
- Error UX: 用 Toasts 取代警告; 添加充电旋转器和进展栏。
Troubleshooting
- 空的OCR结果:尝试高品质的输入、正确的方向或不同的格式(PNG/TIFF)。
- CORS:如果前端分开,请启用 CORS 并使用完整的 API URL。
- 此分類上一篇: HTTPS: Ensure dev cert trust(
dotnet dev-certs https --trust
)如果浏览器阻止混合内容。