오늘날의 디지털 시대에, 이미지에서 텍스트를 추출 할 수있는 능력은 점점 더 중요해지고 있습니다. 스캔 된 문서, 비즈니스 카드, 또는 이미지 기반 데이터의 다른 형태를 다루고 있든,이 정보를 효율적으로 검색하고 조작할 수 있으면 많은 시간과 노력을 절약합니다.이 튜토리얼은 Aspose.OCRASP.NET 코어를 사용하여 상호 작용하는 웹 애플리케이션을 구축하여 사용자가 이미지를 업로드하고 특정 키워드를 검색하며, 강조 된 경기와 함께 실시간 결과를 볼 수 있도록 도와줍니다.

진실의 근원: 아래의 코드와 흐름은 이 문서의 끝 부분에 과 일치합니다 (컨트롤러 끝점, AsposeOcr 사용 및 JSON 응답 형식).

완전한 예제

원칙

  • .NET 8 (또는.NET 6+) SDK
  • 시각 스튜디오 / VS 코드
  • 액세스할 수 있는 방법 Aspose.OCR
  • (선택) 평가 제한을 초과하려는 경우 Aspose 라이센스 파일

단계 1: ASP.NET 코어 MVC 프로젝트 만들기

dotnet new mvc -n ImageTextSearchApp -f net8.0
cd ImageTextSearchApp

# Add Aspose.OCR
dotnet add package Aspose.OCR

** 왜 MVC?** 기어는 컨트롤러를 사용합니다 (HomeController1) 시각, 그리고 클래식 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 및 프로그램

Startup.csProgram.CS를 히드에 포함하여 MVC, 정적 파일, 라우팅 및 HTTPS 리디렉션을 가능하게 합니다.

  • 출발점 : CS
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?}");
            });
        }
    }
}
  • 프로그래밍*
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를 간단한 업로드 양식과 검색 상자로 만드십시오.JavaScript는 파일 + 키워드를 게시합니다. /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 => ({
            '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
        }[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).이미지를 업로드하고, 키워드를 입력하고 Upload & Search를 클릭합니다.

  • Keyword found! 또는 Keyword not found. ( 서버에 의해 생성된)
  • 클라이언트 페이지를 가진 ** 추출 된 텍스트** <mark> 강조

단계 7 : 생산 준비 고려 사항 (선택)

  • 파일 검증: MIME 유형/ 확장을 확인하고 바이러스 백신 검사를 고려하십시오.
  • ** 크기 제한** : 사용하기 RequestSizeLimit (보기) 및 필요한 경우 proxy/web.config 제한을 반환합니다.
  • Cleanup: 정기적으로 오래된 파일을 삭제 wwwroot/uploads.
  • ** 위치**: 여러 언어가 필요한 경우, 서버 측에 OCR 옵션을 설정합니다.
  • Error UX: 알람을 토스트로 대체; 충전 스핀과 진보 바를 추가합니다.

Troubleshooting

  • ** 빈 OCR 결과**: 높은 품질의 입력, 올바른 방향 또는 다른 형식 (PNG/TIFF)을 시도하십시오.
  • CORS: 프론트 엔드가 분리되면 CORS를 활성화하고 전체 API URL을 사용합니다.
  • HTTPS : 확실한 신뢰를 보장하십시오 (dotnet dev-certs https --trust2) 브라우저가 혼합된 콘텐츠를 차단하는 경우

More in this category