Previous Retry Patterns in .NET Core Clean Architecture Next

OCR Implementation in ASP.NET MVC using Tesseract

OCR in ASP.NET MVC

1. Install Tesseract NuGet Package

Install-Package Tesseract -Version 5.2.0

2. Download Tesseract Data Files

Download from Tesseract tessdata GitHub and place the extracted tessdata folder in your project root.

3. Controller Code

using System.IO;
using System.Web;
using System.Web.Mvc;
using Tesseract;

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(HttpPostedFileBase postedFile)
    {
        if (postedFile != null)
        {
            string filePath = Server.MapPath("~/Uploads/" + Path.GetFileName(postedFile.FileName));
            postedFile.SaveAs(filePath);
            string extractText = ExtractTextFromImage(filePath);
            ViewBag.Message = extractText.Replace(Environment.NewLine, "<br />");
        }
        return View();
    }

    private string ExtractTextFromImage(string filePath)
    {
        string path = Server.MapPath("~/") + Path.DirectorySeparatorChar + "tessdata";
        using (var engine = new TesseractEngine(path, "eng", EngineMode.Default))
        {
            using (var img = Pix.LoadFromFile(filePath))
            {
                using (var page = engine.Process(img))
                {
                    return page.GetText();
                }
            }
        }
    }
}
    

4. View (Index.cshtml)

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>OCR Upload</title>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <span>Select File:</span>
        <input type="file" name="postedFile" />
        <input type="submit" value="Upload" />
        <hr />
        <span>@Html.Raw(ViewBag.Message)</span>
    }
</body>
</html>
    

5. Output

Once the image is uploaded, the extracted text will be displayed below the form.

Back to Index
Previous Retry Patterns in .NET Core Clean Architecture Next
*