في العصر الرقمي اليوم، والقدرة على استخراج النص من الصور أصبحت مهمة بشكل متزايد.سواء كنت تتعامل مع المستندات المسح الضوئي، بطاقات الأعمال، أو أي شكل آخر من البيانات القائمة على الصورة، ويمكن أن تبحث وتلاعب هذه المعلومات بكفاءة يمكن أن توفر الكثير من الوقت والجهد.هذا الدليل سوف يقودك من خلال بناء تطبيق الويب التفاعلية باستخدام Aspose.OCR و ASP.NET Core التي تسمح للمستخدمين لتحميل الصور، البحث عن كلمات رئيسية محددة داخل النص المستخرج، ومشاهدة النتائج في الوقت الحقيقي مع المباريات البارزة.

مصدر الحقيقة: يتم توحيد الرمز والتدفق أدناه مع الرماد في نهاية هذه المقالة (نقاط التحكم ، AsposeOcr الاستخدام، وشكل استجابة JSON).

نموذج كامل

المتطلبات

  • نيت 8 (أو .NET 6+) SDK
  • استوديو بصري / VS Code
  • إمكانية الوصول إلى 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

نسمح أيضًا بالملفات الثابتة middleware في 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 and Program

قم بإنشاء Startup.cs و Program.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?}");
            });
        }
    }
}
  • برنامج .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)

إنشاء مشاهدة/المنزل/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 => ({
            '&': '&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).قم بتحميل صورة، أدخل كلمة مفتاحية، ثم انقر فوق تحميل والبحث.

  • Keyword found! أو Keyword not found. (بالتحويل من الخادم)
    • النص المستخرج ** مع جانب العميل <mark> الارتفاع

الخطوة 7: التفكير الجاهز للإنتاج (اختياري)

  • تأكيد الملفات: تحقق من أنواع MIME / التمديدات وتفكر في فحص مكافحة الفيروسات.
    • الحد الأدنى للأحجام *: الاستخدام RequestSizeLimit (مظهر) وإعادة حدود proxy/web.config حسب الحاجة.
  • Cleanup: إزالة الملفات القديمة من wwwroot/uploads.
  • موقع: إذا كنت بحاجة إلى العديد من اللغات، قم بتعيين خيارات اللغة OCR على جانب الخادم.
  • خطأ UX: استبدال التحذيرات بالتوستات؛ إضافة أشرطة التحميل وشرائح التقدم.

Troubleshooting

  • نتائج OCR الفارغة: حاول إدخال أعلى جودة أو التوجه الصحيح أو تنسيق مختلف (PNG/TIFF).
  • CORS: إذا كان الطرف الأمامي منفصلًا، قم بتشغيل CORS واستخدام URL API الكامل.
  • HTTPS: اطمینان dev cert الثقة (dotnet dev-certs https --trustإذا كان المتصفح يمنع المحتوى المختلط.

More in this category