iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🌍️

C#: Using Tablet Camera to Capture Images and Let AI Perform OCR (OCR Edition)

に公開
2026/02/03

This is a continuation of the previous article.
https://zenn.dev/arika/articles/20250911-blazor-ai-with-webcamera-1

Understanding How to Send Requests

Basics

To have the AI perform OCR, you need to send a request with an image.
If you just want to send a simple single request, passing a string works fine, but for more advanced tasks, you need to use ChatMessage.

So, what is ChatMessage?


It is how this is represented programmatically.

Each message in the above image (plus role plus attachments) is represented by a ChatMessage.
For example, the above example can be illustrated as follows:

In short, these are represented using ChatMessage.
These objects are easy to create manually, so you can forge chat history and feed samples to the AI.

For example, the following is a bad example. The output is something other than "No".

// Bad example
var system = new ChatMessage(ChatRole.System,
    "You are a very strict teacher. You must not answer anything other than 'No' even when a student asks a question.");
var user1 = new ChatMessage(ChatRole.User, "I have a question!");
await chatClient.GetResponseAsync([system, user1], new() { Seed = 42 });
// -> Of course, go ahead and ask.

If you modify it as shown below, you get the expected response.

var system = new ChatMessage(ChatRole.System,
    "You are a very strict teacher. You must not answer anything other than 'No' even when a student asks a question.");
// Insert fake conversation
var user1 = new ChatMessage(ChatRole.User, "I want to go to the bathroom");
var answer1 = new ChatMessage(ChatRole.Assistant, "No");
var user2 = new ChatMessage(ChatRole.User, "What day is it today?");
var answer2 = new ChatMessage(ChatRole.Assistant, "No");
// Real question
var user3 = new ChatMessage(ChatRole.User, "I have a question!");
await chatClient.GetResponseAsync(
    [system, user1, answer1, user2, answer2, user3],
    new() { Seed = 42 });
// -> No

In fact, in the later example, we also send sample conversations to get the desired response.

Attaching Images

To attach an image, simply add DataContent to ChatMessage.Contents.

// Prepare image data as byte[] by reading an image file, etc.
byte[] imageData = [];
var prompt = new ChatMessage(ChatRole.User, "Read the text in this image.");
prompt.Contents.Add(new DataContent(imageData, "image/png"));

Forcing JSON Output

Whenever you send a request to the AI, you need to parse the result.
Having the output in JSON format makes it easy to extract values, but sometimes extra output is attached, the format is not as expected, or the AI doesn't output JSON at all.

// Bad example
var responce = "What is 40 squared?";
await chatClient.GetResponseAsync(responce);
// -> 40 squared is 1600.

// Not bad, but unstable example
var responce = """What is 40 squared? Answer in the format {"answer": "(value)"}""";
await chatClient.GetResponseAsync(responce);
// -> {"answer": "1600"}

There is a way to fix this to the desired JSON format.
Simply use the generic version of GetResponseAsync.[1]
I couldn't find this anywhere with a quick Google search in Japanese, but it turns out there is a very convenient method!

public record AnswerResponce(int Answer);

var responce = "What is 40 squared?";
await chatClient.GetResponseAsync<AnswerResponce>(responce, 
    useJsonSchemaResponseFormat: false);
// -> {"answer": 1600}

This time I set useJsonSchemaResponseFormat to false; if you set it to true, you can specify a stricter format using JSON Schema.
...Or at least that's the idea, but I couldn't get a response back from vLLM, so it might not be supported. So this time we'll use false.

Implementing in C#

This time, we'll build a Blazor app.
The user selects an image from their folder, and the AI performs OCR on that image.
Using a tablet's camera would make this longer, so that will be next time.

Program.cs

Basically the same as last time, but this time we'll use DI.

// Omitted
var chatClient = new ChatClient(
    "Qwen/Qwen2-VL-7B-Instruct-AWQ",
    new ApiKeyCredential("test"),
    new OpenAIClientOptions() {
        Endpoint = new Uri("http://localhost:12345/v1"),
    }
).AsIChatClient();

builder.Services.AddChatClient(chatClient).UseLogging();
// Omitted

Reading an Image File

We use the InputFile tag to let the user select an image file.
The result is received as IBrowserFile, which we read and convert to byte[] for use.
Note that the image might be too large to use directly, so we reduce its size with RequestImageFileAsync.

Also, we want to display a thumbnail when an image is selected, so we implement that as well.
Let's also prepare the part that displays the result after receiving it.

<InputFile OnChange="e => FileRecieved(e.File)" />
<br/>

@if (UploadImgBlob != null)
{
    <img src="@UploadImgBlob" />
}

@if (IsParsed)
{
    @if (string.IsNullOrWhiteSpace(ResultLotNo))
    {
        <p>Could not decode the lot number.</p>
    }
    else
    {
        <p>The lot number is <strong>@ResultLotNo</strong>!</p>
    }
}

@code {
    private string? UploadImageBase64;
    private string? ResultLotNo;
    private bool IsParsed = false;

    private async Task FileRecieved(IBrowserFile file)
    {
        await CreateThumbnailAsync(file);
        await TryOcr(file);
    }

    private async Task TryOcr(IBrowserFile file)
    {
        const int MaxImageSize = 512; // Up to 512px
        var resized = await file.RequestImageFileAsync("image/png", MaxImageSize, MaxImageSize);
        var bytes = await LoadImageFromFileAsync(resized);
        // TODO: Attempt OCR
        IsParsed = true;
    }

    private async Task CreateThumbnailAsync(IBrowserFile file)
    {
        const int ThumbnailSize = 512; // Up to 512px
        var smallFile = await file.RequestImageFileAsync("image/png", ThumbnailSize, ThumbnailSize);
        var bufferSmall = await LoadImageFromFileAsync(smallFile);
        UploadImgBlob = $"data:image/png;base64,{Convert.ToBase64String(bufferSmall)}";
        await InvokeAsync(StateHasChanged);
    }

    private async Task<byte[]> LoadImageFromFileAsync(IBrowserFile file)
    {
        using var stream = file.OpenReadStream();
        using var ms = new MemoryStream();
        await stream.CopyToAsync(ms);
        return ms.ToArray();
    }
}

Attempting OCR

As described above, we assemble ChatMessage and send it to the AI.
The system prompt is in English for better accuracy (though I just had the AI translate it).

public class TryOcrService(IChatClient chatClient)
{
    /* Japanese translation:
     * Extract the strings corresponding to the lot number from the provided image and respond in the following JSON format:
     * { "lotno": "(String corresponding to lot number)" }
     * If the appropriate information does not exist within the image, or if you are not confident, apply null instead of generating text.
     */
    private string SystemPrompt = """
    Extract the strings corresponding to the lot number from the provided image and respond in the following JSON format:
    { "lotno": "(String corresponding to lot number)" }
    If the appropriate information does not exist within the image, or if you are not confident, apply null instead of generating text.
    """;

    private string OcrRequestPrompt = " Extract the lot number from the image.";

    // Send a query to the AI to attempt OCR
    // Returns the lot number (null if not found)
    public async Task<string?> TryOcr(byte[] image)
    {
        var systemPrompt = new ChatMessage(ChatRole.System, SystemPrompt);
        // Provide a sample
        var sampleUserPrompt = new ChatMessage(ChatRole.User, OcrRequestPrompt);
        var sampleAssistPrompt = new ChatMessage(ChatRole.Assistant, """{"lotno": "sample"}""");
        // Provide the actual OCR target image
        var userPrompt = new ChatMessage(ChatRole.User, OcrRequestPrompt);
        userPrompt.Contents.Add(new DataContent(image, "image/png"));
        try
        {
            var response = await chatClient.GetResponseAsync<OcrResponse>(
                [systemPrompt, sampleUserPrompt, sampleAssistPrompt, userPrompt],
                new ChatOptions() { Seed = 42 },
                useJsonSchemaResponseFormat: false
            );
            return response.Result.Lotno;
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }
}

internal record OcrResponse(string? Lotno);

Then register this service in DI

builder.Services.AddSingleton<TryOcrService>();

Inject and use it in the component.

@inject TryOcrService OcrService
@code {
    // Omitted
    private async Task TryOcr(IBrowserFile file)
    {
        const int MaxImageSize = 512;
        var resized = await file.RequestImageFileAsync("image/png", MaxImageSize, MaxImageSize);
        var bytes = await LoadImageFromFileAsync(resized);
        ResultLotNo = await OcrService.TryOcr(bytes);
        IsParsed = true;
    }
}

Execution Results

Let's try the photo I used in the previous article.

Looks good!

Let's try another image.

It doesn't say "lot number", but it correctly picked up the identification number.

Finally, let's try a completely unrelated image.

It correctly returned null. Excellent.

Next Time

The code up to this point is available on GitHub.
https://github.com/arika0093/BlazorOcrWithAI/tree/e94595fa87d2b6d8a70ef7e0245060c66f7903f6

Next time, we'll use the tablet's camera to capture images.
https://zenn.dev/arika/articles/20250911-blazor-ai-with-webcamera-3

脚注
  1. The summary also says: Sends chat messages, requesting a response matching the type T. ↩︎

GitHubで編集を提案

Discussion