Skip to content

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

ParameterTypeDefaultPurpose
FormatsBbBarcodeFormatCommonSymbologies to look for. A flags enum.
RegionBbScanRegionFullNormalized sub-rectangle to search.
OptionsBbScannerOptions?nullAdvanced tuning applied under Formats and Region.
TargetFrameRateint15Frames a second to decode.
RequestedWidth / Heightint1280 / 720Camera constraints; the browser may negotiate otherwise.
MaxProcessingSizeint640Longest edge of the image the decoder sees.
FacingBbCameraFacingRearPreferred camera when no device id is given.
DeviceIdstring?nullA specific camera to open.
AutoStartbooltrueOpen the camera as soon as the component is ready.
DuplicateSuppressionWindowTimeSpan?null (2s)How long an identical value stays suppressed. Set, it overrides Options; unset, Options decides, else 2 s.
MaxSymbolsPerFrameint1The most symbols read from one frame or image; more reads every code in view, each reported and outlined on its own.
AfterScanBbAfterScanContinueWhat happens after a reported scan: keep scanning, Pause (camera stays open) or Stop (camera released).
AcceptResultFunc<BbBarcodeResult, bool>?nullDecides which results are reported; one it turns down is ignored as if it were not there.
FeedbackBbScanFeedbackNoneVibrate, Beep or both on every reported scan, where the browser allows it.
ReleaseCameraWhenHiddenboolfalseClose the camera while the page is hidden and reopen it when the page is shown again.
TextsBbScannerTexts?null (English)Every label, status, notice, error message and announcement, for another language.
ShowControlsbooltrueBuilt-in control bar.
ShowStatusBarbooltrueBuilt-in status bar.
ShowReticlebooltrueCorner reticle over the scan region.
ShowMaskbooltrueDim outside the scan region.
HighlightResultsbooltrueOutline a decoded symbol in place.
EnableFileScanningbooltrueOffer still image scanning.
MaxImageFileSizelong32 MBThe largest image file accepted, checked before it is decoded. Zero accepts any size.
FillboolfalseFill the parent instead of keeping the camera's aspect ratio.
AriaLabelstring"Barcode scanner"Accessible name for the region.
CssClassstring?nullExtra classes on the root element.
OverlayRenderFragment<BbScanner>?nullReplaces the reticle; receives the scanner.
MessageTemplateRenderFragment<string>?nullReplaces status and error message rendering.
ControlsContentRenderFragment?nullExtra controls in the built-in bar.
ChildContentRenderFragment?nullArbitrary content over the viewport.
@attributesany-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

EventPayloadRaised when
OnScanBbBarcodeResultA symbol is decoded, accepted by AcceptResult and passes duplicate suppression - from the camera, a picked or dropped image, once per symbol.
OnErrorBbScannerExceptionThe 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.
OnStatusChangedBbScannerStatusThe lifecycle state changes.
OnCameraChangedBbCameraInfoA camera opens, with what was negotiated.
OnDiagnosticsBbScanDiagnosticsAt most twice a second, with the last frame's timings. Costs nothing when not subscribed.

<BbScanner> methods

Called through a @ref to the component.

MethodReturnsDoes
StartAsync(string? deviceId = null)TaskOpens the camera - the given one, else DeviceId, else by Facing - and starts decoding.
StopAsync()TaskStops decoding and releases the camera.
Pause()voidStops decoding, keeps the camera open.
Resume()voidDecodes again after Pause; the symbol in view is reported again unless the window is infinite.
ResetDuplicateFilter()voidForgets 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)TaskReopens 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()TaskOpens 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()ValueTaskReleases 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

PropertyTypeMeaning
StatusBbScannerStatusThe current lifecycle state.
CameraBbCameraInfo?What the browser negotiated for the open camera, or null.
CamerasIReadOnlyList<BbCameraDevice>The cameras found by the last enumeration.
DiagnosticsBbScanDiagnosticsTimings of the most recently decoded frame.
FramesDecodedlongCamera frames decoded since the scanner was created.
FramesWithSymbollongOf those, how many held a symbol, before duplicate suppression.
IsTorchOnboolWhether the torch is lit.
ZoomdoubleThe 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

MemberTypeMeaning
TextstringDecoded value after character set interpretation.
RawBytesReadOnlyMemory<byte>Payload bytes before interpretation.
FormatBbBarcodeFormatThe symbology that produced the value.
TimestampDateTimeOffsetWhen the frame was decoded.
CornersIReadOnlyList<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.
BoundingBoxBbScanRectAxis aligned box around the corners.
FrameWidth / FrameHeightintSize of the frame the value came from.
MetadataBbBarcodeResultMetadata?Symbology specific extras, below; null when the symbology carries none.

BbBarcodeResultMetadata

Every member is null when the symbology does not carry it.

MemberTypeMeaning
SymbolVersionstring?The symbol's version or size: a QR version, a Data Matrix size, M1 to M4, Mode 2 to Mode 5, Stacked.
ErrorCorrectionLevelstring?For example L, M, Q or H for QR Code.
ErrorsCorrectedint?Codewords Reed-Solomon had to repair - a print quality signal.
Eciint?The ECI character set the symbol declared.
IsGs1bool?The symbol carries a GS1 application identifier stream; result.TryGetGs1 splits it into its AIs.
StructuredAppendIndex / Count / Parityint?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.
StructuredAppendFileIdstring?The Macro PDF417 file ID every segment of one file carries.
StructuredAppendIsLastbool?This symbol is the last of its sequence. BbStructuredAppendAssembler puts a sequence back together.
Rows / Columnsint?PDF417 rows and data columns, or the size of the sampled matrix.
Extensionstring?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

MemberMeaning
BbScanRegion(double X, double Y, double Width, double Height)A part of the frame, each value a fraction from 0 to 1.
BbScanRegion.FullThe whole frame, the default.
BbScanRegion.CenteredSquare(double fraction)A centred square of that fraction of the shorter edge, square in pixels on any camera.
KeepSquareNarrows 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

TypeMembers
BbCameraDeviceDeviceId, to open it; Label, its name - generic until permission has been granted once.
BbCameraInfoWhat was negotiated: DeviceId, Label, Width, Height, FrameRate, FacingMode (environment or user), SupportsTorch, TorchOn, SupportsZoom, ZoomMin, ZoomMax, ZoomStep, Zoom.
BbScanDiagnosticsOne frame: Total, and its split into Grayscale, Binarize, Matrix and Linear; DecodedWidth and DecodedHeight, after the region and downsampling; RowsScanned; Decoded; EquivalentFramesPerSecond.
BbScannerExceptionAn Exception with a Kind, a BbScannerErrorKind; FromBrowserError(exception) classifies a getUserMedia rejection.
BbScannerTextsEvery text the scanner shows or announces, each an init property with an English default; Default is the English set. See customisation.

Enums

EnumMembers
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.
BbScannerStatusIdle, Starting, Scanning, Paused, Stopped, Faulted - see lifecycle.
BbAfterScanContinue, Pause, Stop.
BbScanFeedback (flags)None, Vibrate, Beep.
BbCameraFacingAny, Rear, Front.
BbCameraPermissionUnknown, Prompt, Granted, Denied.
BbScannerErrorKindUnknown, PermissionDenied, NoCamera, CameraUnavailable, ConstraintsUnsatisfied, NotSupported, InvalidImage - see errors.
BbPixelFormatRgba32 (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 memberDoes
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.
LastFrameThe BbScanDiagnostics of the last call.
FramesDecoded, FramesWithSymbolCounters since the decoder was created.
DuplicateSuppressionWindow, ResetDuplicateFilter()Its own duplicate filter, changeable while running; pass suppressDuplicates: false to bypass it.
OptionsThe 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.

An unhandled error has occurred. Reload 🗙