TextDetector
Read printed text out of an image or a camera frame with the platform's own recognizer - a serial number, an invoice reference, a label, where typing it in is the alternative.
@inject Bit.Butil.TextDetector textDetectorMDN reference
IsSupported returning false is
the common case; Detect answers with an empty array rather than throwing.
Returns true when the runtime exposes TextDetector. During prerender/SSR the check returns false rather than throwing, so defer it to OnAfterRenderAsync.
@inject Bit.Butil.TextDetector textDetector
if (await textDetector.IsSupported() is false)
{
// keep the manual entry field
}Reads one frame of a video, image or canvas element. What counts as one block is the platform's decision - usually a line, sometimes a paragraph - and each block comes with the box it occupies, which is what you would draw a highlight over before asking the user to confirm.
IAsyncDisposable
Bit.Butil.MediaDevices mediaDevices
Bit.Butil.TextDetector textDetector
<video @ref="_video" autoplay playsinline muted></video>
{
private ElementReference _video;
private MediaStreamHandle? _stream;
private async Task Read()
{
_stream = await mediaDevices.GetUserMedia(
audio: false,
video: true,
videoConstraints: new { facingMode = "environment" }); // rear camera on a phone
await _stream!.AttachTo(_video);
var blocks = await textDetector.Detect(_video);
}
// The camera light stays on until the stream is disposed, whatever the page does.
public async ValueTask DisposeAsync()
{
if (_stream is not null) await _stream.DisposeAsync();
}
}Takes an encoded image's bytes - a PNG or JPEG, not raw pixels. The decoded bitmap is released as soon as the scan finishes; it holds uncompressed pixels, which would be a real leak in a loop.
var blocks = await textDetector.DetectImage(bytes, "image/jpeg");
var everything = string.Join("\n", blocks.Select(b => b.RawValue));API reference
ValueTask<bool> IsSupported()ValueTask<DetectedText[]> Detect(ElementReference element)ValueTask<DetectedText[]> DetectImage(byte[] imageBytes, string mimeType = "image/png")RawValue | X | Y | Width | Height