How to Convert Image to Text in Blazor Server (Simple OCR Example)

Prerequisites

  • .NET 7 or .NET 8, or .NET 9
  • Visual Studio 2022 or newer
  • Basic understanding of Blazor Server
  • Tesseract OCR Engine and language data

Step 1. Create a Blazor Server App.

Open Visual Studio and create a new Blazor Server App project.

Step 2. Install the Required NuGet Package.

Open the Package Manager Console and install the Tesseract wrapper.

Install-Package Tesseract

Step 3. Download Language Data.

  • Go to Tesseract tessdata GitHub repo
  • Download eng. traineddata (for English)
  • Create a folder in your project named tessdata
  • Add the downloaded file to that folder
  • Set its properties: Copy to Output Directory → Copy if newer

Step 4. Download Language Data.

@page "/"
@rendermode InteractiveServer
@using Tesseract
@inject IWebHostEnvironment Env

<PageTitle>Image OCR</PageTitle>

<h1>Image to Text (OCR)</h1>

<InputFile OnChange="HandleFileSelected" />
<br />
<button class="btn btn-primary mt-2" @onclick="ExtractTextFromImage">Extract Text</button>

@if (!string.IsNullOrEmpty(extractedText))
{
    <h3>Extracted Text:</h3>
    <pre>@extractedText</pre>
}

@code {
    private string? imagePath;
    private string? extractedText;

    async Task HandleFileSelected(InputFileChangeEventArgs e)
    {
        var file = e.File;
        var uploads = Path.Combine(Env.WebRootPath, "uploads");

        if (!Directory.Exists(uploads))
            Directory.CreateDirectory(uploads);

        imagePath = Path.Combine(uploads, file.Name);

        using var stream = File.Create(imagePath);
        await file.OpenReadStream().CopyToAsync(stream);
    }

    void ExtractTextFromImage()
    {
        if (string.IsNullOrWhiteSpace(imagePath))
            return;

        var tessDataPath = Path.Combine(Env.ContentRootPath, "tessdata");

        using var engine = new TesseractEngine(tessDataPath, "eng", EngineMode.Default);
        using var img = Pix.LoadFromFile(imagePath);
        using var page = engine.Process(img);

        extractedText = page.GetText();
    }
}

Step 5. Run the Application.

  • Run your Blazor Server app.
  • Navigate to /ocr in the browser.
  • Upload an image file with text.
  • View the extracted text displayed below.

Original Image

Original Image

Output

Output

Up Next
    Ebook Download
    View all
    Learn
    View all