API reference
The whole public surface. Everything is nullable-annotated and documented in XML, so the same text appears in IntelliSense.
The component
<BbScanner> parameters
| Parameter | Type | Default | Purpose |
|---|---|---|---|
| Formats | BbBarcodeFormat | Common | Symbologies to look for. A flags enum. |
| Region | BbScanRegion | Full | Normalized sub-rectangle to search. |
| Options | BbScannerOptions? | null | Advanced tuning applied under Formats and Region. |
| TargetFrameRate | int | 15 | Frames a second to decode. |
| RequestedWidth / Height | int | 1280 / 720 | Camera constraints; the browser may negotiate otherwise. |
| MaxProcessingSize | int | 640 | Longest edge of the image the decoder sees. |
| Facing | BbCameraFacing | Rear | Preferred camera when no device id is given. |
| DeviceId | string? | null | A specific camera to open. |
| AutoStart | bool | true | Open the camera as soon as the component is ready. |
| DuplicateSuppressionWindow | TimeSpan? | null (2s) | How long an identical value stays suppressed. Set, it overrides Options; unset, Options decides, else 2 s. |
| MaxSymbolsPerFrame | int | 1 | The most symbols read from one frame or image; more reads every code in view, each reported and outlined on its own. |
| AfterScan | BbAfterScan | Continue | What happens after a reported scan: keep scanning, Pause (camera stays open) or Stop (camera released). |
| AcceptResult | Func<BbBarcodeResult, bool>? | null | Decides which results are reported; one it turns down is ignored as if it were not there. |
| Feedback | BbScanFeedback | None | Vibrate, Beep or both on every reported scan, where the browser allows it. |
| ReleaseCameraWhenHidden | bool | false | Close the camera while the page is hidden and reopen it when the page is shown again. |
| Texts | BbScannerTexts? | null (English) | Every label, status, notice, error message and announcement, for another language. |
| ShowControls | bool | true | Built-in control bar. |
| ShowStatusBar | bool | true | Built-in status bar. |
| ShowReticle | bool | true | Corner reticle over the scan region. |
| ShowMask | bool | true | Dim outside the scan region. |
| HighlightResults | bool | true | Outline a decoded symbol in place. |
| EnableFileScanning | bool | true | Offer still image scanning. |
| MaxImageFileSize | long | 32 MB | The largest image file accepted, checked before it is decoded. Zero accepts any size. |
| Fill | bool | false | Fill the parent instead of keeping the camera's aspect ratio. |
| AriaLabel | string | "Barcode scanner" | Accessible name for the region. |
| CssClass | string? | null | Extra classes on the root element. |
| Overlay | RenderFragment<BbScanner>? | null | Replaces the reticle; receives the scanner. |
| MessageTemplate | RenderFragment<string>? | null | Replaces status and error message rendering. |
| ControlsContent | RenderFragment? | null | Extra controls in the built-in bar. |
| ChildContent | RenderFragment? | null | Arbitrary content over the viewport. |
| @attributes | any | - | Any other attribute is applied to the root element. A class or style given this way is merged with the component's own rather than replacing it. |
<BbScanner> events
| Event | Payload | Raised when |
|---|---|---|
| OnScan | BbBarcodeResult | A symbol is decoded, accepted by AcceptResult and passes duplicate suppression - from the camera, a picked or dropped image, once per symbol. |
| OnError | BbScannerException | The scanner faults: the camera cannot start or is lost, the options are invalid, or the decoder fails frame after frame. A refused image from the built-in picker is a notice instead. |
| OnStatusChanged | BbScannerStatus | The lifecycle state changes. |
| OnCameraChanged | BbCameraInfo | A camera opens, with what was negotiated. |
| OnDiagnostics | BbScanDiagnostics | At most twice a second, with the last frame's timings. Costs nothing when not subscribed. |
<BbScanner> methods
Called through a @ref to the component.
| Method | Returns | Does |
|---|---|---|
| StartAsync(string? deviceId = null) | Task | Opens the camera - the given one, else DeviceId, else by Facing - and starts decoding. |
| StopAsync() | Task | Stops decoding and releases the camera. |
| Pause() | void | Stops decoding, keeps the camera open. |
| Resume() | void | Decodes again after Pause; the symbol in view is reported again unless the window is infinite. |
| ResetDuplicateFilter() | void | Forgets the values already reported. |
| GetCamerasAsync() | Task<IReadOnlyList<BbCameraDevice>> | Lists the cameras; labels are generic until permission has been granted once. |
| GetCameraPermissionAsync() | Task<BbCameraPermission> | What a start would do, without asking the user. |
| SwitchCameraAsync(string deviceId) | Task | Reopens on another camera without tearing the component down. |
| SetTorchAsync(bool on) | Task<bool> | Turns the torch on or off; whether the browser accepted it. |
| SetZoomAsync(double zoom) | Task<bool> | Sets the zoom, clamped to the camera's range; whether the browser accepted it. |
| OpenFilePickerAsync() | Task | Opens the built-in file picker; results arrive through OnScan. Under Server a call from your own button reaches the page a round trip after the click, which a strict browser may not count as a user gesture; the built-in Scan image button opens the picker in the page itself. |
| ScanImageAsync(Stream image, int maxSymbols = 16, CancellationToken = default) | Task<IReadOnlyList<BbBarcodeResult>> | Scans an encoded image (PNG, JPEG, WebP...) in the browser; returns the symbols, throws InvalidImage. |
| ScanImageAsync(ReadOnlyMemory<byte> image, string? contentType = null, int maxSymbols = 16, CancellationToken = default) | Task<IReadOnlyList<BbBarcodeResult>> | The same, from memory; a contentType that is not an image is refused. |
| ScanCurrentFrameAsync(int maxSymbols = 16) | Task<IReadOnlyList<BbBarcodeResult>> | Reads the camera's current frame at full resolution; throws when the camera is not open. |
| DecodeImage(ReadOnlySpan<byte> pixels, int width, int height, BbPixelFormat format) | BbBarcodeResult? | Decodes the first symbol in pixels the application has. |
| DecodeAllInImage(ReadOnlySpan<byte> pixels, int width, int height, BbPixelFormat format, int maxSymbols = 16) | IReadOnlyList<BbBarcodeResult> | Decodes every symbol in those pixels. |
| DisposeAsync() | ValueTask | Releases the camera and every buffer; Blazor calls it when the component leaves the page. |
The still image calls - ScanImageAsync, ScanCurrentFrameAsync, DecodeImage
and DecodeAllInImage - raise no events, search the whole image whatever the Region,
and use the still image tuning with this scanner's Formats and options.
<BbScanner> properties
| Property | Type | Meaning |
|---|---|---|
| Status | BbScannerStatus | The current lifecycle state. |
| Camera | BbCameraInfo? | What the browser negotiated for the open camera, or null. |
| Cameras | IReadOnlyList<BbCameraDevice> | The cameras found by the last enumeration. |
| Diagnostics | BbScanDiagnostics | Timings of the most recently decoded frame. |
| FramesDecoded | long | Camera frames decoded since the scanner was created. |
| FramesWithSymbol | long | Of those, how many held a symbol, before duplicate suppression. |
| IsTorchOn | bool | Whether the torch is lit. |
| Zoom | double | The current zoom, or zero without zoom support. |
| ProcessingSize | (int Width, int Height) | The size frames are decoded at, after MaxProcessingSize. |
StartAsync is safe to call at any time: a call that arrives while an earlier one
is still waiting for the permission prompt supersedes it, and the superseded request releases
its camera rather than leaving it running. The same holds for StopAsync and for
disposal, so navigating away mid-prompt never leaves the camera indicator lit.
The results and the options
BbBarcodeResult
| Member | Type | Meaning |
|---|---|---|
| Text | string | Decoded value after character set interpretation. |
| RawBytes | ReadOnlyMemory<byte> | Payload bytes before interpretation. |
| Format | BbBarcodeFormat | The symbology that produced the value. |
| Timestamp | DateTimeOffset | When the frame was decoded. |
| Corners | IReadOnlyList<BbScanPoint> | Where the symbol is, in frame pixels: a matrix code's four corners clockwise from its own top-left, or the two ends of the line that read a linear code. |
| BoundingBox | BbScanRect | Axis aligned box around the corners. |
| FrameWidth / FrameHeight | int | Size of the frame the value came from. |
| Metadata | BbBarcodeResultMetadata? | Symbology specific extras, below; null when the symbology carries none. |
BbBarcodeResultMetadata
Every member is null when the symbology does not carry it.
| Member | Type | Meaning |
|---|---|---|
| SymbolVersion | string? | The symbol's version or size: a QR version, a Data Matrix size, M1 to M4, Mode 2 to Mode 5, Stacked. |
| ErrorCorrectionLevel | string? | For example L, M, Q or H for QR Code. |
| ErrorsCorrected | int? | Codewords Reed-Solomon had to repair - a print quality signal. |
| Eci | int? | The ECI character set the symbol declared. |
| IsGs1 | bool? | The symbol carries a GS1 application identifier stream; result.TryGetGs1 splits it into its AIs. |
| StructuredAppendIndex / Count / Parity | int? | Where this symbol sits in a message split across several - from 0 for QR Code and PDF417, from 1 for Data Matrix - and the parity or file identification that groups them. |
| StructuredAppendFileId | string? | The Macro PDF417 file ID every segment of one file carries. |
| StructuredAppendIsLast | bool? | This symbol is the last of its sequence. BbStructuredAppendAssembler puts a sequence back together. |
| Rows / Columns | int? | PDF417 rows and data columns, or the size of the sampled matrix. |
| Extension | string? | The digits of an EAN-2 or EAN-5 add-on beside an EAN or UPC symbol; Text holds the main symbol alone. |
BbScannerOptions
BbBarcodeFormat Formats = BbBarcodeFormat.Common BbScanRegion Region = BbScanRegion.Full int MaxScanLines = 15 // lines per orientation int DownsampleFactor = 1 bool TryHarder = false // exhaustive detection, full rotation sweep bool AllowInverted = false // light on dark symbols bool TryReversedRows = true // linear symbols read right to left bool TryVerticalLines = true // columns and tilted lines, for rotated symbols IReadOnlyCollection<int> ItfLengths = 6..20 even bool Code39CheckDigit = false // require the modulo 43 check character bool Code39ExtendedMode = false // interpret Code 39 as full ASCII bool CodabarStartStop = false // keep Codabar's start and stop letters bool RequireEanExtension = false // hold EAN/UPC back until its add-on is read TimeSpan DuplicateSuppressionWindow = 2 seconds // Zero: every frame; InfiniteTimeSpan: once BbScannerOptions.ForStillImages() // 60 scan lines, TryHarder, AllowInverted, no suppression options.Clone() // take a copy before editing a running scanner's options options.Validate() // throws on an out of range value
ITF has no check character, so ItfLengths is the main defence against a
truncated symbol being reported as a shorter, structurally valid number. Narrow it to the
lengths your application actually uses; an empty collection accepts any even length.
Give a running scanner a new instance, or a Clone(), rather than editing the one it has:
a change to Formats or the options rebuilds its decoder without dropping the camera.
Supporting types
Regions, points and rectangles
| Member | Meaning |
|---|---|
| BbScanRegion(double X, double Y, double Width, double Height) | A part of the frame, each value a fraction from 0 to 1. |
| BbScanRegion.Full | The whole frame, the default. |
| BbScanRegion.CenteredSquare(double fraction) | A centred square of that fraction of the shorter edge, square in pixels on any camera. |
| KeepSquare | Narrows the region to the largest square it holds in a frame's pixels. |
| IsFull, Normalized(), ForFrame(width, height) | Whether it covers the frame; clamped into the unit square; as it applies to a frame of that size. |
| BbScanPoint(float X, float Y) | A point in frame pixels; Distance(a, b). |
| BbScanRect(float X, float Y, float Width, float Height) | A box in frame pixels; Right, Bottom, Center, FromPoints(points). |
Cameras, diagnostics, errors and texts
| Type | Members |
|---|---|
| BbCameraDevice | DeviceId, to open it; Label, its name - generic until permission has been granted once. |
| BbCameraInfo | What was negotiated: DeviceId, Label, Width, Height, FrameRate, FacingMode (environment or user), SupportsTorch, TorchOn, SupportsZoom, ZoomMin, ZoomMax, ZoomStep, Zoom. |
| BbScanDiagnostics | One frame: Total, and its split into Grayscale, Binarize, Matrix and Linear; DecodedWidth and DecodedHeight, after the region and downsampling; RowsScanned; Decoded; EquivalentFramesPerSecond. |
| BbScannerException | An Exception with a Kind, a BbScannerErrorKind; FromBrowserError(exception) classifies a getUserMedia rejection. |
| BbScannerTexts | Every text the scanner shows or announces, each an init property with an English default; Default is the English set. See customisation. |
Enums
| Enum | Members |
|---|---|
| BbBarcodeFormat (flags) | QrCode, MicroQrCode, DataMatrix, Pdf417, MicroPdf417, Aztec, MaxiCode, Code128, Code39, Code93, Codabar, Ean13, Ean8, UpcA, UpcE, Itf, DataBar, DataBarLimited, DataBarExpanded; the sets AllMatrix, AllLinear and All; None. |
| BbScannerStatus | Idle, Starting, Scanning, Paused, Stopped, Faulted - see lifecycle. |
| BbAfterScan | Continue, Pause, Stop. |
| BbScanFeedback (flags) | None, Vibrate, Beep. |
| BbCameraFacing | Any, Rear, Front. |
| BbCameraPermission | Unknown, Prompt, Granted, Denied. |
| BbScannerErrorKind | Unknown, PermissionDenied, NoCamera, CameraUnavailable, ConstraintsUnsatisfied, NotSupported, InvalidImage - see errors. |
| BbPixelFormat | Rgba32 (a canvas's getImageData), Bgra32, Rgb24, Gray8. |
The decoder
Headless use
The decoding pipeline has no dependency on Blazor or on a browser. It runs anywhere .NET runs, which is what makes it testable and benchmarkable.
using var decoder = new BbBarcodeDecoder(new BbScannerOptions { Formats = BbBarcodeFormat.QrCode | BbBarcodeFormat.DataMatrix, DuplicateSuppressionWindow = TimeSpan.Zero, }); var result = decoder.Decode(rgbaPixels, width, height, BbPixelFormat.Rgba32); if (result is not null) { Console.WriteLine($"{result.Format}: {result.Text}"); Console.WriteLine($"took {decoder.LastFrame.Total.TotalMilliseconds:0.00} ms"); }
| BbBarcodeDecoder member | Does |
|---|---|
| new BbBarcodeDecoder(BbScannerOptions? options = null) | Builds the readers for options.Formats, once. Dispose it to return its pooled buffers. |
| Decode(pixels, width, height, format, suppressDuplicates = true) | The first symbol in packed pixels, or null. |
| DecodeAll(pixels, width, height, format, maxSymbols = 16, suppressDuplicates = true) | Every symbol, matrix symbols first. |
| Decode(in BbLuminanceView view, ...) / DecodeAll(in BbLuminanceView view, ...) | The same, from a frame that is already 8 bit grayscale. |
| LastFrame | The BbScanDiagnostics of the last call. |
| FramesDecoded, FramesWithSymbol | Counters since the decoder was created. |
| DuplicateSuppressionWindow, ResetDuplicateFilter() | Its own duplicate filter, changeable while running; pass suppressDuplicates: false to bypass it. |
| Options | The options it was created with. |
A decoder is not thread safe: give each thread its own. Every result carries the same
BbBarcodeResult the component reports.
Building blocks
Every reader implements IBbRowDecoder for a linear code or
IBbMatrixDecoder for a two dimensional one, and can be driven directly by a
pipeline of your own. BbBarcodeDecoder composes the built-in readers from
Formats and does not accept others.
public interface IBbRowDecoder { BbBarcodeFormat Formats { get; } BbSymbolDecodeResult? DecodeRow(int rowNumber, BbBitRow row, BbBarcodeFormat enabledFormats); } public interface IBbMatrixDecoder { BbBarcodeFormat Formats { get; } BbSymbolDecodeResult? Decode(BbBitMatrix image, BbMatrixDecodeOptions options); }
Binarisation follows the same shape: IBbBinarizer has one implementation tuned for
matrix codes, one for linear rows and a global histogram fallback, each usable on its own.