Add barcode-detector-api-polyfill dependency and update environment variable declarations in SvelteKit project
CI / build (push) Has been skipped
CI / deploy (push) Successful in 1m50s

This commit is contained in:
eewing
2026-02-17 14:58:53 -06:00
parent cff20a652a
commit 9022114c8d
2137 changed files with 201996 additions and 762 deletions
@@ -0,0 +1,6 @@
import { Exception, Result } from '@zxing/library';
import { IScannerControls } from './IScannerControls';
/**
* Callback format for continuous decode scan.
*/
export declare type DecodeContinuouslyCallback = (result: Result | undefined, error: Exception | undefined, controls: IScannerControls) => void;
@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=DecodeContinuouslyCallback.js.map
@@ -0,0 +1 @@
{"version":3,"file":"DecodeContinuouslyCallback.js","sourceRoot":"","sources":["../../../src/common/DecodeContinuouslyCallback.ts"],"names":[],"mappings":""}
@@ -0,0 +1,25 @@
import { LuminanceSource } from '@zxing/library';
export declare class HTMLCanvasElementLuminanceSource extends LuminanceSource {
private canvas;
private static DEGREE_TO_RADIANS;
private static makeBufferFromCanvasImageData;
private static toGrayscaleBuffer;
private buffer;
private tempCanvasElement?;
constructor(canvas: HTMLCanvasElement);
getRow(y: number, row: Uint8ClampedArray): Uint8ClampedArray;
getMatrix(): Uint8ClampedArray;
isCropSupported(): boolean;
crop(left: number, top: number, width: number, height: number): LuminanceSource;
/**
* This is always true, since the image is a gray-scale image.
*
* @return true
*/
isRotateSupported(): boolean;
rotateCounterClockwise(): LuminanceSource;
rotateCounterClockwise45(): LuminanceSource;
invert(): LuminanceSource;
private getTempCanvasElement;
private rotate;
}
@@ -0,0 +1,132 @@
import { IllegalArgumentException, InvertedLuminanceSource, LuminanceSource, } from '@zxing/library';
/**/
export class HTMLCanvasElementLuminanceSource extends LuminanceSource {
constructor(canvas) {
super(canvas.width, canvas.height);
this.canvas = canvas;
this.tempCanvasElement = null;
this.buffer = HTMLCanvasElementLuminanceSource.makeBufferFromCanvasImageData(canvas);
}
static makeBufferFromCanvasImageData(canvas) {
let canvasCtx;
try {
canvasCtx = canvas.getContext('2d', { willReadFrequently: true });
}
catch (e) {
canvasCtx = canvas.getContext('2d');
}
if (!canvasCtx) {
throw new Error('Couldn\'t get canvas context.');
}
const imageData = canvasCtx.getImageData(0, 0, canvas.width, canvas.height);
return HTMLCanvasElementLuminanceSource.toGrayscaleBuffer(imageData.data, canvas.width, canvas.height);
}
static toGrayscaleBuffer(imageBuffer, width, height) {
const grayscaleBuffer = new Uint8ClampedArray(width * height);
for (let i = 0, j = 0, length = imageBuffer.length; i < length; i += 4, j++) {
let gray;
const alpha = imageBuffer[i + 3];
// The color of fully-transparent pixels is irrelevant. They are often, technically, fully-transparent
// black (0 alpha, and then 0 RGB). They are often used, of course as the "white" area in a
// barcode image. Force any such pixel to be white:
if (alpha === 0) {
gray = 0xFF;
}
else {
const pixelR = imageBuffer[i];
const pixelG = imageBuffer[i + 1];
const pixelB = imageBuffer[i + 2];
// .299R + 0.587G + 0.114B (YUV/YIQ for PAL and NTSC),
// (306*R) >> 10 is approximately equal to R*0.299, and so on.
// 0x200 >> 10 is 0.5, it implements rounding.
// tslint:disable-next-line:no-bitwise
gray = (306 * pixelR + 601 * pixelG + 117 * pixelB + 0x200) >> 10;
}
grayscaleBuffer[j] = gray;
}
return grayscaleBuffer;
}
getRow(y /*int*/, row) {
if (y < 0 || y >= this.getHeight()) {
throw new IllegalArgumentException('Requested row is outside the image: ' + y);
}
const width = this.getWidth();
const start = y * width;
if (row === null) {
row = this.buffer.slice(start, start + width);
}
else {
if (row.length < width) {
row = new Uint8ClampedArray(width);
}
// The underlying raster of image consists of bytes with the luminance values
// TODO: can avoid set/slice?
row.set(this.buffer.slice(start, start + width));
}
return row;
}
getMatrix() {
return this.buffer;
}
isCropSupported() {
return true;
}
crop(left /*int*/, top /*int*/, width /*int*/, height /*int*/) {
super.crop(left, top, width, height);
return this;
}
/**
* This is always true, since the image is a gray-scale image.
*
* @return true
*/
isRotateSupported() {
return true;
}
rotateCounterClockwise() {
this.rotate(-90);
return this;
}
rotateCounterClockwise45() {
this.rotate(-45);
return this;
}
invert() {
return new InvertedLuminanceSource(this);
}
getTempCanvasElement() {
if (null === this.tempCanvasElement) {
const tempCanvasElement = this.canvas.ownerDocument.createElement('canvas');
tempCanvasElement.width = this.canvas.width;
tempCanvasElement.height = this.canvas.height;
this.tempCanvasElement = tempCanvasElement;
}
return this.tempCanvasElement;
}
rotate(angle) {
const tempCanvasElement = this.getTempCanvasElement();
if (!tempCanvasElement) {
throw new Error('Could not create a Canvas element.');
}
const angleRadians = angle * HTMLCanvasElementLuminanceSource.DEGREE_TO_RADIANS;
// Calculate and set new dimensions for temp canvas
const width = this.canvas.width;
const height = this.canvas.height;
const newWidth = Math.ceil(Math.abs(Math.cos(angleRadians)) * width + Math.abs(Math.sin(angleRadians)) * height);
const newHeight = Math.ceil(Math.abs(Math.sin(angleRadians)) * width + Math.abs(Math.cos(angleRadians)) * height);
tempCanvasElement.width = newWidth;
tempCanvasElement.height = newHeight;
const tempContext = tempCanvasElement.getContext('2d');
if (!tempContext) {
throw new Error('Could not create a Canvas Context element.');
}
// Draw at center of temp canvas to prevent clipping of image data
tempContext.translate(newWidth / 2, newHeight / 2);
tempContext.rotate(angleRadians);
tempContext.drawImage(this.canvas, width / -2, height / -2);
this.buffer = HTMLCanvasElementLuminanceSource.makeBufferFromCanvasImageData(tempCanvasElement);
return this;
}
}
HTMLCanvasElementLuminanceSource.DEGREE_TO_RADIANS = Math.PI / 180;
//# sourceMappingURL=HTMLCanvasElementLuminanceSource.js.map
@@ -0,0 +1 @@
{"version":3,"file":"HTMLCanvasElementLuminanceSource.js","sourceRoot":"","sources":["../../../src/common/HTMLCanvasElementLuminanceSource.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,wBAAwB,EACxB,uBAAuB,EACvB,eAAe,GAChB,MAAM,gBAAgB,CAAC;AAExB,IAAI;AACJ,MAAM,OAAO,gCAAiC,SAAQ,eAAe;IA+CnE,YAA2B,MAAyB;QAClD,KAAK,CAAC,MAAM,CAAC,KAAK,EAAE,MAAM,C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AAC,CAAC,CAAC,CAAC;QAC5D,IAAI,CAAC,MAAM,GAAG,gCAAgC,CAAC,6BAA6B,CAAC,iBAAiB,CAAC,CAAC;QAChG,OAAO,IAAI,CAAC;IACd,CAAC;;AApJc,kDAAiB,GAAG,IAAI,CAAC,EAAE,GAAG,GAAG,CAAC"}
@@ -0,0 +1,4 @@
/**
* HTML elements that can be decoded.
*/
export declare type HTMLVisualMediaElement = HTMLVideoElement | HTMLImageElement;
+2
View File
@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=HTMLVisualMediaElement.js.map
@@ -0,0 +1 @@
{"version":3,"file":"HTMLVisualMediaElement.js","sourceRoot":"","sources":["../../../src/common/HTMLVisualMediaElement.ts"],"names":[],"mappings":""}
+30
View File
@@ -0,0 +1,30 @@
export interface IScannerControls {
/**
* Stops the scan process loop.
*/
stop: () => void;
/**
* @experimental This is highly unstable and Torch support is not ready on browsers. Use at YOUR OWN risk.
*/
switchTorch?: (onOff: boolean) => Promise<void>;
/**
* Allows to apply constraints to all tracks or filtered tracks in the stream.
* @experimental
*/
streamVideoConstraintsApply?: (constraints: MediaTrackConstraints, trackFilter?: (track: MediaStreamTrack) => MediaStreamTrack[]) => void;
/**
* Get the desired track constraints.
* @experimental
*/
streamVideoConstraintsGet?: (trackFilter: (track: MediaStreamTrack) => MediaStreamTrack[]) => MediaTrackConstraints;
/**
* Get the desired track settings.
* @experimental
*/
streamVideoSettingsGet?: (trackFilter: (track: MediaStreamTrack) => MediaStreamTrack[]) => MediaTrackSettings;
/**
* Get the desired track capabilities.
* @experimental
*/
streamVideoCapabilitiesGet?: (trackFilter: (track: MediaStreamTrack) => MediaStreamTrack[]) => MediaTrackCapabilities;
}
+2
View File
@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=IScannerControls.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"IScannerControls.js","sourceRoot":"","sources":["../../../src/common/IScannerControls.ts"],"names":[],"mappings":""}
+8
View File
@@ -0,0 +1,8 @@
/**
* If navigator is present.
*/
export declare function hasNavigator(): boolean;
/**
* If enumerateDevices under navigator is supported.
*/
export declare function canEnumerateDevices(): boolean;
+19
View File
@@ -0,0 +1,19 @@
/**
* If navigator is present.
*/
export function hasNavigator() {
return typeof navigator !== 'undefined';
}
/**
* If mediaDevices under navigator is supported.
*/
function isMediaDevicesSupported() {
return hasNavigator() && !!navigator.mediaDevices;
}
/**
* If enumerateDevices under navigator is supported.
*/
export function canEnumerateDevices() {
return !!(isMediaDevicesSupported() && navigator.mediaDevices.enumerateDevices);
}
//# sourceMappingURL=navigator-utils.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"navigator-utils.js","sourceRoot":"","sources":["../../../src/common/navigator-utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,UAAU,YAAY;IAC1B,OAAO,OAAO,SAAS,KAAK,WAAW,CAAC;AAC1C,CAAC;AACD;;GAEG;AACH,SAAS,uBAAuB;IAC9B,OAAO,YAAY,EAAE,IAAI,CAAC,CAAC,SAAS,CAAC,YAAY,CAAC;AACpD,CAAC;AACD;;GAEG;AACH,MAAM,UAAU,mBAAmB;IACjC,OAAO,CAAC,CAAC,CAAC,uBAAuB,EAAE,IAAI,SAAS,CAAC,YAAY,CAAC,gBAAgB,CAAC,CAAC;AAClF,CAAC"}
+14
View File
@@ -0,0 +1,14 @@
export { BarcodeFormat } from '@zxing/library';
export * from './common/HTMLCanvasElementLuminanceSource';
export * from './common/HTMLVisualMediaElement';
export * from './common/IScannerControls';
export * from './readers/BrowserAztecCodeReader';
export * from './readers/BrowserMultiFormatOneDReader';
export * from './readers/BrowserCodeReader';
export * from './readers/BrowserDatamatrixCodeReader';
export * from './readers/BrowserMultiFormatReader';
export * from './readers/BrowserPDF417Reader';
export * from './readers/BrowserQRCodeReader';
export * from './readers/IBrowserCodeReaderOptions';
export * from './writers/BrowserCodeSvgWriter';
export * from './writers/BrowserQRCodeSvgWriter';
+20
View File
@@ -0,0 +1,20 @@
// public API
// core
export { BarcodeFormat } from '@zxing/library';
// common
export * from './common/HTMLCanvasElementLuminanceSource';
export * from './common/HTMLVisualMediaElement';
export * from './common/IScannerControls';
// readers
export * from './readers/BrowserAztecCodeReader';
export * from './readers/BrowserMultiFormatOneDReader';
export * from './readers/BrowserCodeReader';
export * from './readers/BrowserDatamatrixCodeReader';
export * from './readers/BrowserMultiFormatReader';
export * from './readers/BrowserPDF417Reader';
export * from './readers/BrowserQRCodeReader';
export * from './readers/IBrowserCodeReaderOptions';
// writers
export * from './writers/BrowserCodeSvgWriter';
export * from './writers/BrowserQRCodeSvgWriter';
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,aAAa;AAEb,OAAO;AACP,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAE/C,SAAS;AACT,cAAc,2CAA2C,CAAC;AAC1D,cAAc,iCAAiC,CAAC;AAChD,cAAc,2BAA2B,CAAC;AAE1C,UAAU;AACV,cAAc,kCAAkC,CAAC;AACjD,cAAc,wCAAwC,CAAC;AACvD,cAAc,6BAA6B,CAAC;AAC5C,cAAc,uCAAuC,CAAC;AACtD,cAAc,oCAAoC,CAAC;AACnD,cAAc,+BAA+B,CAAC;AAC9C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,qCAAqC,CAAC;AAEpD,UAAU;AACV,cAAc,gCAAgC,CAAC;AAC/C,cAAc,kCAAkC,CAAC"}
+15
View File
@@ -0,0 +1,15 @@
import { DecodeHintType } from '@zxing/library';
import { BrowserCodeReader } from './BrowserCodeReader';
import { IBrowserCodeReaderOptions } from './IBrowserCodeReaderOptions';
/**
* Aztec Code reader to use from browser.
*
* @class BrowserAztecCodeReader
* @extends {BrowserCodeReader}
*/
export declare class BrowserAztecCodeReader extends BrowserCodeReader {
/**
* Creates an instance of BrowserAztecCodeReader.
*/
constructor(hints?: Map<DecodeHintType, any>, options?: IBrowserCodeReaderOptions);
}
+17
View File
@@ -0,0 +1,17 @@
import { AztecCodeReader } from '@zxing/library';
import { BrowserCodeReader } from './BrowserCodeReader';
/**
* Aztec Code reader to use from browser.
*
* @class BrowserAztecCodeReader
* @extends {BrowserCodeReader}
*/
export class BrowserAztecCodeReader extends BrowserCodeReader {
/**
* Creates an instance of BrowserAztecCodeReader.
*/
constructor(hints, options) {
super(new AztecCodeReader(), hints, options);
}
}
//# sourceMappingURL=BrowserAztecCodeReader.js.map
@@ -0,0 +1 @@
{"version":3,"file":"BrowserAztecCodeReader.js","sourceRoot":"","sources":["../../../src/readers/BrowserAztecCodeReader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAkB,MAAM,gBAAgB,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAGxD;;;;;GAKG;AACH,MAAM,OAAO,sBAAuB,SAAQ,iBAAiB;IAC3D;;OAEG;IACH,YACE,KAAgC,EAChC,OAAmC;QAEnC,KAAK,CAAC,IAAI,eAAe,EAAE,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;IAC/C,CAAC;CACF"}
+283
View File
@@ -0,0 +1,283 @@
import { BarcodeFormat, BinaryBitmap, DecodeHintType, Reader, Result } from '@zxing/library';
import { DecodeContinuouslyCallback } from '../common/DecodeContinuouslyCallback';
import { HTMLVisualMediaElement } from '../common/HTMLVisualMediaElement';
import { IScannerControls } from '../common/IScannerControls';
import { IBrowserCodeReaderOptions } from './IBrowserCodeReaderOptions';
/**
* Base class for browser code reader.
*/
export declare class BrowserCodeReader {
protected readonly reader: Reader;
hints: Map<DecodeHintType, any>;
/**
* Allows to change the possible formats the decoder should
* search for while scanning some image. Useful for changing
* the possible formats during BrowserCodeReader::scan.
*/
set possibleFormats(formats: BarcodeFormat[]);
/**
* Defines what the videoElement src will be.
*
* @param videoElement
* @param stream The stream to be added as a source.
*/
static addVideoSource(videoElement: HTMLVideoElement, stream: MediaStream): void;
/**
* Enables or disables the torch in a media stream.
*
* @experimental This doesn't work across all browsers and is still a Draft.
*/
static mediaStreamSetTorch(track: MediaStreamTrack, onOff: boolean): Promise<void>;
/**
* Checks if the stream has torch support.
*/
static mediaStreamIsTorchCompatible(params: MediaStream): boolean;
/**
*
* @param track The media stream track that will be checked for compatibility.
*/
static mediaStreamIsTorchCompatibleTrack(track: MediaStreamTrack): boolean;
/**
* Checks if the given video element is currently playing.
*/
static isVideoPlaying(video: HTMLVideoElement): boolean;
/**
* Searches and validates a media element.
*/
static getMediaElement(mediaElementId: string, type: string): HTMLVisualMediaElement;
/**
* Receives a source and makes sure to return a Video Element from it or fail.
*/
static createVideoElement(videoThingy?: HTMLVideoElement | string): HTMLVideoElement;
/**
* Receives a source and makes sure to return an Image Element from it or fail.
*/
static prepareImageElement(imageSource?: HTMLImageElement | string): HTMLImageElement;
/**
* Sets a HTMLVideoElement for scanning or creates a new one.
*
* @param videoElem The HTMLVideoElement to be set.
*/
static prepareVideoElement(videoElem?: HTMLVideoElement | string): HTMLVideoElement;
/**
* Checks if and HTML image is loaded.
*/
static isImageLoaded(img: HTMLImageElement): boolean;
/**
* Creates a binaryBitmap based in a canvas.
*
* @param canvas HTML canvas element containing the image source draw.
*/
static createBinaryBitmapFromCanvas(canvas: HTMLCanvasElement): BinaryBitmap;
/**
* Overwriting this allows you to manipulate the snapshot image in anyway you want before decode.
*/
static drawImageOnCanvas(canvasElementContext: CanvasRenderingContext2D, srcElement: HTMLVisualMediaElement): void;
static getMediaElementDimensions(mediaElement: HTMLVisualMediaElement): {
height: number;
width: number;
};
/**
* 🖌 Prepares the canvas for capture and scan frames.
*/
static createCaptureCanvas(mediaElement: HTMLVisualMediaElement): HTMLCanvasElement;
/**
* Just tries to play the video and logs any errors.
* The play call is only made is the video is not already playing.
*/
static tryPlayVideo(videoElement: HTMLVideoElement): Promise<boolean>;
/**
* Creates a canvas and draws the current image frame from the media element on it.
*
* @param mediaElement HTML media element to extract an image frame from.
*/
static createCanvasFromMediaElement(mediaElement: HTMLVisualMediaElement): HTMLCanvasElement;
/**
* Creates a binaryBitmap based in some image source.
*
* @param mediaElement HTML element containing drawable image source.
*/
static createBinaryBitmapFromMediaElem(mediaElement: HTMLVisualMediaElement): BinaryBitmap;
static destroyImageElement(imageElement: HTMLImageElement): void;
/**
* Lists all the available video input devices.
*/
static listVideoInputDevices(): Promise<MediaDeviceInfo[]>;
/**
* Let's you find a device using it's Id.
*/
static findDeviceById(deviceId: string): Promise<MediaDeviceInfo | undefined>;
/**
* Unbinds a HTML video src property.
*/
static cleanVideoSource(videoElement: HTMLVideoElement): void;
/**
* Stops all media streams that are created.
*/
static releaseAllStreams(): void;
/**
* Waits for a video to load and then hits play on it.
* To accomplish that, it binds listeners and callbacks to the video element.
*
* @param element The video element.
* @param callbackFn Callback invoked when the video is played.
*/
protected static playVideoOnLoadAsync(element: HTMLVideoElement, timeout: number): Promise<boolean>;
/**
* Sets the new stream and request a new decoding-with-delay.
*
* @param stream The stream to be shown in the video element.
* @param decodeFn A callback for the decode method.
*/
protected static attachStreamToVideo(stream: MediaStream, preview?: string | HTMLVideoElement, previewPlayTimeout?: number): Promise<HTMLVideoElement>;
/**
* Keeps track to created media streams.
* @private there is no need this array to be accessible from outside.
*/
private static streamTracker;
/**
* Returns a Promise that resolves when the given image element loads.
*/
private static _waitImageLoad;
/**
* Checks if the `callbackFn` is defined, otherwise throws.
*/
private static checkCallbackFnOrThrow;
/**
* Standard method to dispose a media stream object.
*/
private static disposeMediaStream;
/**
* BrowserCodeReader specific configuration options.
*/
protected readonly options: IBrowserCodeReaderOptions;
/**
* Creates an instance of BrowserCodeReader.
* @param {Reader} reader The reader instance to decode the barcode
* @param hints Holds the hints the user sets for the Reader.
*/
constructor(reader: Reader, hints?: Map<DecodeHintType, any>, options?: IBrowserCodeReaderOptions);
/**
* Gets the BinaryBitmap for ya! (and decodes it)
*/
decode(element: HTMLVisualMediaElement): Result;
/**
* Call the encapsulated readers decode
*/
decodeBitmap(binaryBitmap: BinaryBitmap): Result;
/**
* Decodes some barcode from a canvas!
*/
decodeFromCanvas(canvas: HTMLCanvasElement): Result;
/**
* Decodes something from an image HTML element.
*/
decodeFromImageElement(source: string | HTMLImageElement): Promise<Result>;
/**
* Decodes an image from a URL.
*/
decodeFromImageUrl(url?: string): Promise<Result>;
/**
* Continuously tries to decode the barcode from a stream obtained from the given constraints
* while showing the video in the specified video element.
*
* @param {MediaStream} [constraints] the media stream constraints to get s valid media stream to decode from
* @param {string|HTMLVideoElement} [previewElem] the video element in page where to show the video while
* decoding. Can be either an element id or directly an HTMLVideoElement. Can be undefined, in
* which case no video will be shown.
*/
decodeFromConstraints(constraints: MediaStreamConstraints, previewElem: string | HTMLVideoElement | undefined, callbackFn: DecodeContinuouslyCallback): Promise<IScannerControls>;
/**
* In one attempt, tries to decode the barcode from a stream obtained from the given constraints
* while showing the video in the specified video element.
*
* @param {MediaStream} [constraints] the media stream constraints to get s valid media stream to decode from
* @param {string|HTMLVideoElement} [preview] the video element in page where to show the video
* while decoding. Can be either an element id or directly an HTMLVideoElement. Can be undefined,
* in which case no video will be shown.
*/
decodeFromStream(stream: MediaStream, preview: string | HTMLVideoElement | undefined, callbackFn: DecodeContinuouslyCallback): Promise<IScannerControls>;
/**
* Continuously tries to decode the barcode from the device specified by device while showing
* the video in the specified video element.
*
* @param {string|null} [deviceId] the id of one of the devices obtained after calling
* getVideoInputDevices. Can be undefined, in this case it will decode from one of the
* available devices, preferring the main camera (environment facing) if available.
* @param {string|HTMLVideoElement|null} [video] the video element in page where to show the video
* while decoding. Can be either an element id or directly an HTMLVideoElement. Can be undefined,
* in which case no video will be shown.
*/
decodeFromVideoDevice(deviceId: string | undefined, previewElem: string | HTMLVideoElement | undefined, callbackFn: DecodeContinuouslyCallback): Promise<IScannerControls>;
/**
* Decodes something from an image HTML element.
*/
decodeFromVideoElement(source: string | HTMLVideoElement, callbackFn: DecodeContinuouslyCallback): Promise<IScannerControls>;
/**
* Decodes a video from a URL until it ends.
*/
decodeFromVideoUrl(url: string, callbackFn: DecodeContinuouslyCallback): Promise<IScannerControls>;
/**
* In one attempt, tries to decode the barcode from a stream obtained from the given
* constraints while showing the video in the specified video element.
*
* @param constraints the media stream constraints to get s valid media stream to decode from
* @param videoSource the video element in page where to show the video while decoding.
* Can be either an element id or directly an HTMLVideoElement. Can be undefined,
* in which case no video will be shown.
* The decoding result.
*/
decodeOnceFromConstraints(constraints: MediaStreamConstraints, videoSource?: string | HTMLVideoElement): Promise<Result>;
/**
* In one attempt, tries to decode the barcode from a stream obtained from the given
* constraints while showing the video in the specified video element.
*
* @param {MediaStream} [constraints] the media stream constraints to get s valid media stream to decode from
* @param {string|HTMLVideoElement} [video] the video element in page where to show the video while decoding.
* Can be either an element id or directly an HTMLVideoElement. Can be undefined,
* in which case no video will be shown.
*/
decodeOnceFromStream(stream: MediaStream, preview?: string | HTMLVideoElement): Promise<Result>;
/**
* In one attempt, tries to decode the barcode from the device specified by deviceId
* while showing the video in the specified video element.
*
* @param deviceId the id of one of the devices obtained after calling getVideoInputDevices.
* Can be undefined, in this case it will decode from one of the available devices,
* preferring the main camera (environment facing) if available.
* @param videoSource the video element in page where to show the video while decoding.
* Can be either an element id or directly an HTMLVideoElement. Can be undefined,
* in which case no video will be shown.
*/
decodeOnceFromVideoDevice(deviceId?: string, videoSource?: string | HTMLVideoElement): Promise<Result>;
/**
* Decodes something from an image HTML element.
*/
decodeOnceFromVideoElement(source: string | HTMLVideoElement): Promise<Result>;
/**
* Decodes a video from a URL.
*/
decodeOnceFromVideoUrl(url: string): Promise<Result>;
/**
* Tries to decode from the video input until it finds some value.
*/
scanOneResult(element: HTMLVisualMediaElement, retryIfNotFound?: boolean, retryIfChecksumError?: boolean, retryIfFormatError?: boolean): Promise<Result>;
/**
* Continuously decodes from video input.
*
* @param element HTML element to scan/decode from. It will not be disposed or destroyed.
* @param callbackFn Called after every scan attempt, being it successful or errored.
* @param finalizeCallback Called after scan process reaches the end or stop is called.
*/
scan(element: HTMLVisualMediaElement, callbackFn: DecodeContinuouslyCallback, finalizeCallback?: (error?: Error) => void): IScannerControls;
/**
* Waits for the image to load and then tries to decode it.
*/
private _decodeOnLoadImage;
/**
* Get MediaStream from browser to be used.
* @param constraints constraints the media stream constraints to get s valid media stream to decode from.
* @private For private use.
*/
private getUserMedia;
}
+909
View File
@@ -0,0 +1,909 @@
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { ArgumentException, BinaryBitmap, ChecksumException, DecodeHintType, FormatException, HybridBinarizer, NotFoundException, } from '@zxing/library';
import { HTMLCanvasElementLuminanceSource } from '../common/HTMLCanvasElementLuminanceSource';
import { canEnumerateDevices, hasNavigator } from '../common/navigator-utils';
const defaultOptions = {
delayBetweenScanAttempts: 500,
delayBetweenScanSuccess: 500,
tryPlayVideoTimeout: 5000,
};
/**
* Base class for browser code reader.
*/
export class BrowserCodeReader {
/**
* Creates an instance of BrowserCodeReader.
* @param {Reader} reader The reader instance to decode the barcode
* @param hints Holds the hints the user sets for the Reader.
*/
constructor(reader, hints = new Map(), options = {}) {
this.reader = reader;
this.hints = hints;
this.options = Object.assign(Object.assign({}, defaultOptions), options);
}
/**
* Allows to change the possible formats the decoder should
* search for while scanning some image. Useful for changing
* the possible formats during BrowserCodeReader::scan.
*/
set possibleFormats(formats) {
this.hints.set(DecodeHintType.POSSIBLE_FORMATS, formats);
}
/**
* Defines what the videoElement src will be.
*
* @param videoElement
* @param stream The stream to be added as a source.
*/
static addVideoSource(videoElement, stream) {
// Older browsers may not have `srcObject`
try {
// @note Throws Exception if interrupted by a new loaded request
videoElement.srcObject = stream;
}
catch (err) {
console.error("got interrupted by new loading request");
}
}
/**
* Enables or disables the torch in a media stream.
*
* @experimental This doesn't work across all browsers and is still a Draft.
*/
static mediaStreamSetTorch(track, onOff) {
return __awaiter(this, void 0, void 0, function* () {
yield track.applyConstraints({
advanced: [{
fillLightMode: onOff ? 'flash' : 'off',
torch: onOff ? true : false,
}],
});
});
}
/**
* Checks if the stream has torch support.
*/
static mediaStreamIsTorchCompatible(params) {
const tracks = params.getVideoTracks();
for (const track of tracks) {
if (BrowserCodeReader.mediaStreamIsTorchCompatibleTrack(track)) {
return true;
}
}
return false;
}
/**
*
* @param track The media stream track that will be checked for compatibility.
*/
static mediaStreamIsTorchCompatibleTrack(track) {
try {
const capabilities = track.getCapabilities();
return 'torch' in capabilities;
}
catch (err) {
// some browsers may not be compatible with ImageCapture
// so we are ignoring this for now.
// tslint:disable-next-line:no-console
console.error(err);
// tslint:disable-next-line:no-console
console.warn('Your browser may be not fully compatible with WebRTC and/or ImageCapture specs. Torch will not be available.');
return false;
}
}
/**
* Checks if the given video element is currently playing.
*/
static isVideoPlaying(video) {
return video.currentTime > 0 && !video.paused && video.readyState > 2;
}
/**
* Searches and validates a media element.
*/
static getMediaElement(mediaElementId, type) {
const mediaElement = document.getElementById(mediaElementId);
if (!mediaElement) {
throw new ArgumentException(`element with id '${mediaElementId}' not found`);
}
if (mediaElement.nodeName.toLowerCase() !== type.toLowerCase()) {
throw new ArgumentException(`element with id '${mediaElementId}' must be an ${type} element`);
}
return mediaElement;
}
/**
* Receives a source and makes sure to return a Video Element from it or fail.
*/
static createVideoElement(videoThingy) {
if (videoThingy instanceof HTMLVideoElement) {
return videoThingy;
}
if (typeof videoThingy === 'string') {
return BrowserCodeReader.getMediaElement(videoThingy, 'video');
}
if (!videoThingy && typeof document !== 'undefined') {
const videoElement = document.createElement('video');
videoElement.width = 200;
videoElement.height = 200;
return videoElement;
}
throw new Error('Couldn\'t get videoElement from videoSource!');
}
/**
* Receives a source and makes sure to return an Image Element from it or fail.
*/
static prepareImageElement(imageSource) {
if (imageSource instanceof HTMLImageElement) {
return imageSource;
}
if (typeof imageSource === 'string') {
return BrowserCodeReader.getMediaElement(imageSource, 'img');
}
if (typeof imageSource === 'undefined') {
const imageElement = document.createElement('img');
imageElement.width = 200;
imageElement.height = 200;
return imageElement;
}
throw new Error('Couldn\'t get imageElement from imageSource!');
}
/**
* Sets a HTMLVideoElement for scanning or creates a new one.
*
* @param videoElem The HTMLVideoElement to be set.
*/
static prepareVideoElement(videoElem) {
const videoElement = BrowserCodeReader.createVideoElement(videoElem);
// @todo the following lines should not always be done this way, should conditionally
// change according were we created the element or not
// Needed for iOS 11
videoElement.setAttribute('autoplay', 'true');
videoElement.setAttribute('muted', 'true');
videoElement.setAttribute('playsinline', 'true');
return videoElement;
}
/**
* Checks if and HTML image is loaded.
*/
static isImageLoaded(img) {
// During the onload event, IE correctly identifies any images that
// weren't downloaded as not complete. Others should too. Gecko-based
// browsers act like NS4 in that they report this incorrectly.
if (!img.complete) {
return false;
}
// However, they do have two very useful properties: naturalWidth and
// naturalHeight. These give the true size of the image. If it failed
// to load, either of these should be zero.
if (img.naturalWidth === 0) {
return false;
}
// No other way of checking: assume its ok.
return true;
}
/**
* Creates a binaryBitmap based in a canvas.
*
* @param canvas HTML canvas element containing the image source draw.
*/
static createBinaryBitmapFromCanvas(canvas) {
const luminanceSource = new HTMLCanvasElementLuminanceSource(canvas);
const hybridBinarizer = new HybridBinarizer(luminanceSource);
return new BinaryBitmap(hybridBinarizer);
}
/**
* Overwriting this allows you to manipulate the snapshot image in anyway you want before decode.
*/
static drawImageOnCanvas(canvasElementContext, srcElement) {
canvasElementContext.drawImage(srcElement, 0, 0);
}
static getMediaElementDimensions(mediaElement) {
if (mediaElement instanceof HTMLVideoElement) {
return {
height: mediaElement.videoHeight,
width: mediaElement.videoWidth,
};
}
if (mediaElement instanceof HTMLImageElement) {
return {
height: mediaElement.naturalHeight || mediaElement.height,
width: mediaElement.naturalWidth || mediaElement.width,
};
}
throw new Error('Couldn\'t find the Source\'s dimensions!');
}
/**
* 🖌 Prepares the canvas for capture and scan frames.
*/
static createCaptureCanvas(mediaElement) {
if (!mediaElement) {
throw new ArgumentException('Cannot create a capture canvas without a media element.');
}
if (typeof document === 'undefined') {
throw new Error('The page "Document" is undefined, make sure you\'re running in a browser.');
}
const canvasElement = document.createElement('canvas');
const { width, height } = BrowserCodeReader.getMediaElementDimensions(mediaElement);
canvasElement.style.width = width + 'px';
canvasElement.style.height = height + 'px';
canvasElement.width = width;
canvasElement.height = height;
return canvasElement;
}
/**
* Just tries to play the video and logs any errors.
* The play call is only made is the video is not already playing.
*/
static tryPlayVideo(videoElement) {
return __awaiter(this, void 0, void 0, function* () {
if (videoElement === null || videoElement === void 0 ? void 0 : videoElement.ended) {
// tslint:disable-next-line:no-console
console.error('Trying to play video that has ended.');
return false;
}
if (BrowserCodeReader.isVideoPlaying(videoElement)) {
// tslint:disable-next-line:no-console
console.warn('Trying to play video that is already playing.');
return true;
}
try {
yield videoElement.play();
return true;
}
catch (error) {
// tslint:disable-next-line:no-console
console.warn('It was not possible to play the video.', error);
return false;
}
});
}
/**
* Creates a canvas and draws the current image frame from the media element on it.
*
* @param mediaElement HTML media element to extract an image frame from.
*/
static createCanvasFromMediaElement(mediaElement) {
const canvas = BrowserCodeReader.createCaptureCanvas(mediaElement);
const ctx = canvas.getContext('2d');
if (!ctx) {
throw new Error('Couldn\'t find Canvas 2D Context.');
}
BrowserCodeReader.drawImageOnCanvas(ctx, mediaElement);
return canvas;
}
/**
* Creates a binaryBitmap based in some image source.
*
* @param mediaElement HTML element containing drawable image source.
*/
static createBinaryBitmapFromMediaElem(mediaElement) {
const canvas = BrowserCodeReader.createCanvasFromMediaElement(mediaElement);
return BrowserCodeReader.createBinaryBitmapFromCanvas(canvas);
}
static destroyImageElement(imageElement) {
imageElement.src = '';
imageElement.removeAttribute('src');
imageElement = undefined;
}
/**
* Lists all the available video input devices.
*/
static listVideoInputDevices() {
return __awaiter(this, void 0, void 0, function* () {
if (!hasNavigator()) {
throw new Error('Can\'t enumerate devices, navigator is not present.');
}
if (!canEnumerateDevices()) {
throw new Error('Can\'t enumerate devices, method not supported.');
}
const devices = yield navigator.mediaDevices.enumerateDevices();
const videoDevices = [];
for (const device of devices) {
const kind = device.kind === 'video' ? 'videoinput' : device.kind;
if (kind !== 'videoinput') {
continue;
}
const deviceId = device.deviceId || device.id;
const label = device.label || `Video device ${videoDevices.length + 1}`;
const groupId = device.groupId;
const videoDevice = { deviceId, label, kind, groupId };
videoDevices.push(videoDevice);
}
return videoDevices;
});
}
/**
* Let's you find a device using it's Id.
*/
static findDeviceById(deviceId) {
return __awaiter(this, void 0, void 0, function* () {
const devices = yield BrowserCodeReader.listVideoInputDevices();
if (!devices) {
return;
}
return devices.find((x) => x.deviceId === deviceId);
});
}
/**
* Unbinds a HTML video src property.
*/
static cleanVideoSource(videoElement) {
if (!videoElement) {
return;
}
// forgets about that element 😢
try {
videoElement.srcObject = null;
}
catch (err) {
videoElement.src = '';
}
if (videoElement) {
videoElement.removeAttribute('src');
}
}
/**
* Stops all media streams that are created.
*/
static releaseAllStreams() {
if (BrowserCodeReader.streamTracker.length !== 0) {
// tslint:disable-next-line:no-console
BrowserCodeReader.streamTracker.forEach((mediaStream) => {
mediaStream.getTracks().forEach((track) => track.stop());
});
}
BrowserCodeReader.streamTracker = [];
}
/**
* Waits for a video to load and then hits play on it.
* To accomplish that, it binds listeners and callbacks to the video element.
*
* @param element The video element.
* @param callbackFn Callback invoked when the video is played.
*/
static playVideoOnLoadAsync(element, timeout) {
return __awaiter(this, void 0, void 0, function* () {
// if canplay was already fired, we won't know when to play, so just give it a try
const isPlaying = yield BrowserCodeReader.tryPlayVideo(element);
if (isPlaying) {
return true;
}
return new Promise((resolve, reject) => {
// waits 3 seconds or rejects.
const timeoutId = setTimeout(() => {
if (BrowserCodeReader.isVideoPlaying(element)) {
// if video is playing then we had success, just ignore
return;
}
reject(false);
element.removeEventListener('canplay', videoCanPlayListener);
}, timeout);
/**
* Should contain the current registered listener for video loaded-metadata,
* used to unregister that listener when needed.
*/
const videoCanPlayListener = () => {
BrowserCodeReader.tryPlayVideo(element).then((hasPlayed) => {
clearTimeout(timeoutId);
element.removeEventListener('canplay', videoCanPlayListener);
resolve(hasPlayed);
});
};
// both should be unregistered after called
element.addEventListener('canplay', videoCanPlayListener);
});
});
}
/**
* Sets the new stream and request a new decoding-with-delay.
*
* @param stream The stream to be shown in the video element.
* @param decodeFn A callback for the decode method.
*/
static attachStreamToVideo(stream, preview, previewPlayTimeout = 5000) {
return __awaiter(this, void 0, void 0, function* () {
const videoElement = BrowserCodeReader.prepareVideoElement(preview);
BrowserCodeReader.addVideoSource(videoElement, stream);
yield BrowserCodeReader.playVideoOnLoadAsync(videoElement, previewPlayTimeout);
return videoElement;
});
}
/**
* Returns a Promise that resolves when the given image element loads.
*/
static _waitImageLoad(element) {
return new Promise((resolve, reject) => {
const timeout = 10000;
// waits 10 seconds or rejects.
const timeoutId = setTimeout(() => {
if (BrowserCodeReader.isImageLoaded(element)) {
// if video is playing then we had success, just ignore
return;
}
// removes the listener
element.removeEventListener('load', imageLoadedListener);
// rejects the load
reject();
}, timeout);
const imageLoadedListener = () => {
clearTimeout(timeoutId);
// removes the listener
element.removeEventListener('load', imageLoadedListener);
// resolves the load
resolve();
};
element.addEventListener('load', imageLoadedListener);
});
}
/**
* Checks if the `callbackFn` is defined, otherwise throws.
*/
static checkCallbackFnOrThrow(callbackFn) {
if (!callbackFn) {
throw new ArgumentException('`callbackFn` is a required parameter, you cannot capture results without it.');
}
}
/**
* Standard method to dispose a media stream object.
*/
static disposeMediaStream(stream) {
stream.getVideoTracks().forEach((x) => x.stop());
stream = undefined;
}
/**
* Gets the BinaryBitmap for ya! (and decodes it)
*/
decode(element) {
// get binary bitmap for decode function
const canvas = BrowserCodeReader.createCanvasFromMediaElement(element);
return this.decodeFromCanvas(canvas);
}
/**
* Call the encapsulated readers decode
*/
decodeBitmap(binaryBitmap) {
return this.reader.decode(binaryBitmap, this.hints);
}
/**
* Decodes some barcode from a canvas!
*/
decodeFromCanvas(canvas) {
const binaryBitmap = BrowserCodeReader.createBinaryBitmapFromCanvas(canvas);
return this.decodeBitmap(binaryBitmap);
}
/**
* Decodes something from an image HTML element.
*/
decodeFromImageElement(source) {
return __awaiter(this, void 0, void 0, function* () {
if (!source) {
throw new ArgumentException('An image element must be provided.');
}
const element = BrowserCodeReader.prepareImageElement(source);
// onLoad will remove it's callback once done
// we do not need to dispose or destroy the image
// since it came from the user
return yield this._decodeOnLoadImage(element);
});
}
/**
* Decodes an image from a URL.
*/
decodeFromImageUrl(url) {
return __awaiter(this, void 0, void 0, function* () {
if (!url) {
throw new ArgumentException('An URL must be provided.');
}
const element = BrowserCodeReader.prepareImageElement();
// loads the image.
element.src = url;
try {
// it waits the task so we can destroy the created image after
return yield this.decodeFromImageElement(element);
}
finally {
// we created this element, so we destroy it
BrowserCodeReader.destroyImageElement(element);
}
});
}
/**
* Continuously tries to decode the barcode from a stream obtained from the given constraints
* while showing the video in the specified video element.
*
* @param {MediaStream} [constraints] the media stream constraints to get s valid media stream to decode from
* @param {string|HTMLVideoElement} [previewElem] the video element in page where to show the video while
* decoding. Can be either an element id or directly an HTMLVideoElement. Can be undefined, in
* which case no video will be shown.
*/
decodeFromConstraints(constraints, previewElem, callbackFn) {
return __awaiter(this, void 0, void 0, function* () {
BrowserCodeReader.checkCallbackFnOrThrow(callbackFn);
const stream = yield this.getUserMedia(constraints);
try {
return yield this.decodeFromStream(stream, previewElem, callbackFn);
}
catch (error) {
BrowserCodeReader.disposeMediaStream(stream);
throw error;
}
});
}
/**
* In one attempt, tries to decode the barcode from a stream obtained from the given constraints
* while showing the video in the specified video element.
*
* @param {MediaStream} [constraints] the media stream constraints to get s valid media stream to decode from
* @param {string|HTMLVideoElement} [preview] the video element in page where to show the video
* while decoding. Can be either an element id or directly an HTMLVideoElement. Can be undefined,
* in which case no video will be shown.
*/
decodeFromStream(stream, preview, callbackFn) {
return __awaiter(this, void 0, void 0, function* () {
BrowserCodeReader.checkCallbackFnOrThrow(callbackFn);
const timeout = this.options.tryPlayVideoTimeout;
const video = yield BrowserCodeReader.attachStreamToVideo(stream, preview, timeout);
// IF we receive a stream from the user, it's not our job to dispose it
const finalizeCallback = () => {
// stops video tracks and releases the stream reference
BrowserCodeReader.disposeMediaStream(stream);
// this video was just a preview, so in order
// to release the stream we gotta stop showing
// it (the stream) in the video element
BrowserCodeReader.cleanVideoSource(video);
};
const originalControls = this.scan(video, callbackFn, finalizeCallback);
const videoTracks = stream.getVideoTracks();
const controls = Object.assign(Object.assign({}, originalControls), { stop() {
originalControls.stop();
},
streamVideoConstraintsApply(constraints, trackFilter) {
return __awaiter(this, void 0, void 0, function* () {
const tracks = trackFilter ? videoTracks.filter(trackFilter) : videoTracks;
for (const track of tracks) {
yield track.applyConstraints(constraints);
}
});
},
streamVideoConstraintsGet(trackFilter) {
return videoTracks.find(trackFilter).getConstraints();
},
streamVideoSettingsGet(trackFilter) {
return videoTracks.find(trackFilter).getSettings();
},
streamVideoCapabilitiesGet(trackFilter) {
return videoTracks.find(trackFilter).getCapabilities();
} });
const isTorchAvailable = BrowserCodeReader.mediaStreamIsTorchCompatible(stream);
if (isTorchAvailable) {
const torchTrack = videoTracks === null || videoTracks === void 0 ? void 0 : videoTracks.find((t) => BrowserCodeReader.mediaStreamIsTorchCompatibleTrack(t));
const switchTorch = (onOff) => __awaiter(this, void 0, void 0, function* () {
yield BrowserCodeReader.mediaStreamSetTorch(torchTrack, onOff);
});
controls.switchTorch = switchTorch;
controls.stop = () => __awaiter(this, void 0, void 0, function* () {
originalControls.stop();
yield switchTorch(false);
});
}
return controls;
});
}
/**
* Continuously tries to decode the barcode from the device specified by device while showing
* the video in the specified video element.
*
* @param {string|null} [deviceId] the id of one of the devices obtained after calling
* getVideoInputDevices. Can be undefined, in this case it will decode from one of the
* available devices, preferring the main camera (environment facing) if available.
* @param {string|HTMLVideoElement|null} [video] the video element in page where to show the video
* while decoding. Can be either an element id or directly an HTMLVideoElement. Can be undefined,
* in which case no video will be shown.
*/
decodeFromVideoDevice(deviceId, previewElem, callbackFn) {
return __awaiter(this, void 0, void 0, function* () {
BrowserCodeReader.checkCallbackFnOrThrow(callbackFn);
let videoConstraints;
if (!deviceId) {
videoConstraints = { facingMode: 'environment' };
}
else {
videoConstraints = { deviceId: { exact: deviceId } };
}
const constraints = { video: videoConstraints };
return yield this.decodeFromConstraints(constraints, previewElem, callbackFn);
});
}
/**
* Decodes something from an image HTML element.
*/
decodeFromVideoElement(source, callbackFn) {
return __awaiter(this, void 0, void 0, function* () {
BrowserCodeReader.checkCallbackFnOrThrow(callbackFn);
if (!source) {
throw new ArgumentException('A video element must be provided.');
}
// we do not create a video element
const element = BrowserCodeReader.prepareVideoElement(source);
const timeout = this.options.tryPlayVideoTimeout;
// plays the video
yield BrowserCodeReader.playVideoOnLoadAsync(element, timeout);
// starts decoding after played the video
return this.scan(element, callbackFn);
});
}
/**
* Decodes a video from a URL until it ends.
*/
decodeFromVideoUrl(url, callbackFn) {
return __awaiter(this, void 0, void 0, function* () {
BrowserCodeReader.checkCallbackFnOrThrow(callbackFn);
if (!url) {
throw new ArgumentException('An URL must be provided.');
}
// creates a new element
const element = BrowserCodeReader.prepareVideoElement();
// starts loading the video
element.src = url;
const finalizeCallback = () => {
// dispose created video element
BrowserCodeReader.cleanVideoSource(element);
};
const timeout = this.options.tryPlayVideoTimeout;
// plays the video
yield BrowserCodeReader.playVideoOnLoadAsync(element, timeout);
// starts decoding after played the video
const controls = this.scan(element, callbackFn, finalizeCallback);
return controls;
});
}
/**
* In one attempt, tries to decode the barcode from a stream obtained from the given
* constraints while showing the video in the specified video element.
*
* @param constraints the media stream constraints to get s valid media stream to decode from
* @param videoSource the video element in page where to show the video while decoding.
* Can be either an element id or directly an HTMLVideoElement. Can be undefined,
* in which case no video will be shown.
* The decoding result.
*/
decodeOnceFromConstraints(constraints, videoSource) {
return __awaiter(this, void 0, void 0, function* () {
const stream = yield this.getUserMedia(constraints);
return yield this.decodeOnceFromStream(stream, videoSource);
});
}
/**
* In one attempt, tries to decode the barcode from a stream obtained from the given
* constraints while showing the video in the specified video element.
*
* @param {MediaStream} [constraints] the media stream constraints to get s valid media stream to decode from
* @param {string|HTMLVideoElement} [video] the video element in page where to show the video while decoding.
* Can be either an element id or directly an HTMLVideoElement. Can be undefined,
* in which case no video will be shown.
*/
decodeOnceFromStream(stream, preview) {
return __awaiter(this, void 0, void 0, function* () {
const receivedPreview = Boolean(preview);
const video = yield BrowserCodeReader.attachStreamToVideo(stream, preview);
try {
const result = yield this.scanOneResult(video);
return result;
}
finally {
if (!receivedPreview) {
BrowserCodeReader.cleanVideoSource(video);
}
}
});
}
/**
* In one attempt, tries to decode the barcode from the device specified by deviceId
* while showing the video in the specified video element.
*
* @param deviceId the id of one of the devices obtained after calling getVideoInputDevices.
* Can be undefined, in this case it will decode from one of the available devices,
* preferring the main camera (environment facing) if available.
* @param videoSource the video element in page where to show the video while decoding.
* Can be either an element id or directly an HTMLVideoElement. Can be undefined,
* in which case no video will be shown.
*/
decodeOnceFromVideoDevice(deviceId, videoSource) {
return __awaiter(this, void 0, void 0, function* () {
let videoConstraints;
if (!deviceId) {
videoConstraints = { facingMode: 'environment' };
}
else {
videoConstraints = { deviceId: { exact: deviceId } };
}
const constraints = { video: videoConstraints };
return yield this.decodeOnceFromConstraints(constraints, videoSource);
});
}
/**
* Decodes something from an image HTML element.
*/
decodeOnceFromVideoElement(source) {
return __awaiter(this, void 0, void 0, function* () {
if (!source) {
throw new ArgumentException('A video element must be provided.');
}
// we do not create a video element
const element = BrowserCodeReader.prepareVideoElement(source);
const timeout = this.options.tryPlayVideoTimeout;
// plays the video
yield BrowserCodeReader.playVideoOnLoadAsync(element, timeout);
// starts decoding after played the video
return yield this.scanOneResult(element);
});
}
/**
* Decodes a video from a URL.
*/
decodeOnceFromVideoUrl(url) {
return __awaiter(this, void 0, void 0, function* () {
if (!url) {
throw new ArgumentException('An URL must be provided.');
}
// creates a new element
const element = BrowserCodeReader.prepareVideoElement();
// starts loading the video
element.src = url;
const task = this.decodeOnceFromVideoElement(element);
try {
// it waits the task so we can destroy the created image after
return yield task;
}
finally {
// we created this element, so we destroy it
BrowserCodeReader.cleanVideoSource(element);
}
});
}
/**
* Tries to decode from the video input until it finds some value.
*/
scanOneResult(element, retryIfNotFound = true, retryIfChecksumError = true, retryIfFormatError = true) {
return new Promise((resolve, reject) => {
// reuses the scan API, but returns at the first successful result
this.scan(element, (result, error, controls) => {
if (result) {
// good result, returning
resolve(result);
controls.stop();
return;
}
if (error) {
// checks if it should retry
if (error instanceof NotFoundException && retryIfNotFound) {
return;
}
if (error instanceof ChecksumException && retryIfChecksumError) {
return;
}
if (error instanceof FormatException && retryIfFormatError) {
return;
}
// not re-trying
controls.stop(); // stops scan loop
reject(error); // returns the error
}
});
});
}
/**
* Continuously decodes from video input.
*
* @param element HTML element to scan/decode from. It will not be disposed or destroyed.
* @param callbackFn Called after every scan attempt, being it successful or errored.
* @param finalizeCallback Called after scan process reaches the end or stop is called.
*/
scan(element, callbackFn, finalizeCallback) {
BrowserCodeReader.checkCallbackFnOrThrow(callbackFn);
/**
* The HTML canvas element, used to draw the video or image's frame for decoding.
*/
let captureCanvas = BrowserCodeReader.createCaptureCanvas(element);
/**
* The HTML canvas element context.
*/
let captureCanvasContext;
try {
captureCanvasContext = captureCanvas.getContext('2d', { willReadFrequently: true });
}
catch (e) {
captureCanvasContext = captureCanvas.getContext('2d');
}
// cannot proceed w/o this
if (!captureCanvasContext) {
throw new Error('Couldn\'t create canvas for visual element scan.');
}
const disposeCanvas = () => {
captureCanvasContext = undefined;
captureCanvas = undefined;
};
let stopScan = false;
let lastTimeoutId;
// can be called to break the scan loop
const stop = () => {
stopScan = true;
clearTimeout(lastTimeoutId);
disposeCanvas();
if (finalizeCallback) {
finalizeCallback();
}
};
// created for extensibility
const controls = { stop };
// this async loop allows infinite (or almost? maybe) scans
const loop = () => {
if (stopScan) {
// no need to clear timeouts as none was create yet in this scope.
return;
}
try {
BrowserCodeReader.drawImageOnCanvas(captureCanvasContext, element);
const result = this.decodeFromCanvas(captureCanvas);
callbackFn(result, undefined, controls);
lastTimeoutId = setTimeout(loop, this.options.delayBetweenScanSuccess);
}
catch (error) {
callbackFn(undefined, error, controls);
const isChecksumError = error instanceof ChecksumException;
const isFormatError = error instanceof FormatException;
const isNotFound = error instanceof NotFoundException;
if (isChecksumError || isFormatError || isNotFound) {
// trying again
lastTimeoutId = setTimeout(loop, this.options.delayBetweenScanAttempts);
return;
}
// not trying again
disposeCanvas();
if (finalizeCallback) {
finalizeCallback(error);
}
}
};
// starts the async loop
loop();
return controls;
}
/**
* Waits for the image to load and then tries to decode it.
*/
_decodeOnLoadImage(element) {
return __awaiter(this, void 0, void 0, function* () {
const isImageLoaded = BrowserCodeReader.isImageLoaded(element);
if (!isImageLoaded) {
yield BrowserCodeReader._waitImageLoad(element);
}
return this.decode(element);
});
}
/**
* Get MediaStream from browser to be used.
* @param constraints constraints the media stream constraints to get s valid media stream to decode from.
* @private For private use.
*/
getUserMedia(constraints) {
return __awaiter(this, void 0, void 0, function* () {
const stream = yield navigator.mediaDevices.getUserMedia(constraints);
BrowserCodeReader.streamTracker.push(stream);
return stream;
});
}
}
/**
* Keeps track to created media streams.
* @private there is no need this array to be accessible from outside.
*/
BrowserCodeReader.streamTracker = [];
//# sourceMappingURL=BrowserCodeReader.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,12 @@
import { DecodeHintType } from '@zxing/library';
import { BrowserCodeReader } from './BrowserCodeReader';
import { IBrowserCodeReaderOptions } from './IBrowserCodeReaderOptions';
/**
* QR Code reader to use from browser.
*/
export declare class BrowserDatamatrixCodeReader extends BrowserCodeReader {
/**
* Creates an instance of BrowserQRCodeReader.
*/
constructor(hints?: Map<DecodeHintType, any>, options?: IBrowserCodeReaderOptions);
}
@@ -0,0 +1,14 @@
import { DataMatrixReader } from '@zxing/library';
import { BrowserCodeReader } from './BrowserCodeReader';
/**
* QR Code reader to use from browser.
*/
export class BrowserDatamatrixCodeReader extends BrowserCodeReader {
/**
* Creates an instance of BrowserQRCodeReader.
*/
constructor(hints, options) {
super(new DataMatrixReader(), hints, options);
}
}
//# sourceMappingURL=BrowserDatamatrixCodeReader.js.map
@@ -0,0 +1 @@
{"version":3,"file":"BrowserDatamatrixCodeReader.js","sourceRoot":"","sources":["../../../src/readers/BrowserDatamatrixCodeReader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAkB,MAAM,gBAAgB,CAAC;AAClE,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAGxD;;GAEG;AACH,MAAM,OAAO,2BAA4B,SAAQ,iBAAiB;IAChE;;OAEG;IACH,YACE,KAAgC,EAChC,OAAmC;QAEnC,KAAK,CAAC,IAAI,gBAAgB,EAAE,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;IAChD,CAAC;CACF"}
@@ -0,0 +1,14 @@
import { DecodeHintType } from '@zxing/library';
import { BrowserCodeReader } from './BrowserCodeReader';
import { IBrowserCodeReaderOptions } from './IBrowserCodeReaderOptions';
/**
* Reader to be used for any One Dimension type barcode.
*/
export declare class BrowserMultiFormatOneDReader extends BrowserCodeReader {
/**
* Creates an instance of BrowserBarcodeReader.
* @param {Map<DecodeHintType, any>} hints?
* @param options
*/
constructor(hints?: Map<DecodeHintType, any>, options?: IBrowserCodeReaderOptions);
}
@@ -0,0 +1,16 @@
import { MultiFormatOneDReader } from '@zxing/library';
import { BrowserCodeReader } from './BrowserCodeReader';
/**
* Reader to be used for any One Dimension type barcode.
*/
export class BrowserMultiFormatOneDReader extends BrowserCodeReader {
/**
* Creates an instance of BrowserBarcodeReader.
* @param {Map<DecodeHintType, any>} hints?
* @param options
*/
constructor(hints, options) {
super(new MultiFormatOneDReader(hints), hints, options);
}
}
//# sourceMappingURL=BrowserMultiFormatOneDReader.js.map
@@ -0,0 +1 @@
{"version":3,"file":"BrowserMultiFormatOneDReader.js","sourceRoot":"","sources":["../../../src/readers/BrowserMultiFormatOneDReader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AACvE,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAGxD;;GAEG;AACH,MAAM,OAAO,4BAA6B,SAAQ,iBAAiB;IACjE;;;;OAIG;IACH,YAAmB,KAAgC,EAAE,OAAmC;QACtF,KAAK,CAAC,IAAI,qBAAqB,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;IAC1D,CAAC;CACF"}
@@ -0,0 +1,17 @@
import { BarcodeFormat, BinaryBitmap, DecodeHintType, MultiFormatReader, Result } from '@zxing/library';
import { BrowserCodeReader } from './BrowserCodeReader';
import { IBrowserCodeReaderOptions } from './IBrowserCodeReaderOptions';
export declare class BrowserMultiFormatReader extends BrowserCodeReader {
set possibleFormats(formats: BarcodeFormat[]);
protected readonly reader: MultiFormatReader;
constructor(hints?: Map<DecodeHintType, any>, options?: IBrowserCodeReaderOptions);
/**
* Overwrite decodeBitmap to call decodeWithState, which will pay
* attention to the hints set in the constructor function
*/
decodeBitmap(binaryBitmap: BinaryBitmap): Result;
/**
* Allows to change hints in runtime.
*/
setHints(hints: Map<DecodeHintType, any>): void;
}
+29
View File
@@ -0,0 +1,29 @@
import { DecodeHintType, MultiFormatReader, } from '@zxing/library';
import { BrowserCodeReader } from './BrowserCodeReader';
export class BrowserMultiFormatReader extends BrowserCodeReader {
constructor(hints, options) {
const reader = new MultiFormatReader();
reader.setHints(hints);
super(reader, hints, options);
this.reader = reader;
}
set possibleFormats(formats) {
this.hints.set(DecodeHintType.POSSIBLE_FORMATS, formats);
this.reader.setHints(this.hints);
}
/**
* Overwrite decodeBitmap to call decodeWithState, which will pay
* attention to the hints set in the constructor function
*/
decodeBitmap(binaryBitmap) {
return this.reader.decodeWithState(binaryBitmap);
}
/**
* Allows to change hints in runtime.
*/
setHints(hints) {
this.hints = hints;
this.reader.setHints(this.hints);
}
}
//# sourceMappingURL=BrowserMultiFormatReader.js.map
@@ -0,0 +1 @@
{"version":3,"file":"BrowserMultiFormatReader.js","sourceRoot":"","sources":["../../../src/readers/BrowserMultiFormatReader.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,cAAc,EACd,iBAAiB,GAElB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAGxD,MAAM,OAAO,wBAAyB,SAAQ,iBAAiB;IAS7D,YACE,KAAgC,EAChC,OAAmC;QAEnC,MAAM,MAAM,GAAG,IAAI,iBAAiB,EAAE,CAAC;QACvC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;QACvB,KAAK,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;QAC9B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;IAfD,IAAI,eAAe,CAAC,OAAwB;QAC1C,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,cAAc,CAAC,gBAAgB,EAAE,OAAO,CAAC,CAAC;QACzD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACnC,CAAC;IAcD;;;OAGG;IACI,YAAY,CAAC,YAA0B;QAC5C,OAAO,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,YAAY,CAAC,CAAC;IACnD,CAAC;IAED;;OAEG;IACI,QAAQ,CAAC,KAA+B;QAC7C,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACnC,CAAC;CACF"}
+12
View File
@@ -0,0 +1,12 @@
import { DecodeHintType } from '@zxing/library';
import { BrowserCodeReader } from './BrowserCodeReader';
import { IBrowserCodeReaderOptions } from './IBrowserCodeReaderOptions';
/**
* QR Code reader to use from browser.
*/
export declare class BrowserPDF417Reader extends BrowserCodeReader {
/**
* Creates an instance of BrowserPDF417Reader.
*/
constructor(hints?: Map<DecodeHintType, any>, options?: IBrowserCodeReaderOptions);
}
+14
View File
@@ -0,0 +1,14 @@
import { PDF417Reader } from '@zxing/library';
import { BrowserCodeReader } from './BrowserCodeReader';
/**
* QR Code reader to use from browser.
*/
export class BrowserPDF417Reader extends BrowserCodeReader {
/**
* Creates an instance of BrowserPDF417Reader.
*/
constructor(hints, options) {
super(new PDF417Reader(), hints, options);
}
}
//# sourceMappingURL=BrowserPDF417Reader.js.map
@@ -0,0 +1 @@
{"version":3,"file":"BrowserPDF417Reader.js","sourceRoot":"","sources":["../../../src/readers/BrowserPDF417Reader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAGxD;;GAEG;AACH,MAAM,OAAO,mBAAoB,SAAQ,iBAAiB;IACxD;;OAEG;IACH,YACE,KAAgC,EAChC,OAAmC;QAEnC,KAAK,CAAC,IAAI,YAAY,EAAE,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;IAC5C,CAAC;CACF"}
+12
View File
@@ -0,0 +1,12 @@
import { DecodeHintType } from '@zxing/library';
import { BrowserCodeReader } from './BrowserCodeReader';
import { IBrowserCodeReaderOptions } from './IBrowserCodeReaderOptions';
/**
* QR Code reader to use from browser.
*/
export declare class BrowserQRCodeReader extends BrowserCodeReader {
/**
* Creates an instance of BrowserQRCodeReader.
*/
constructor(hints?: Map<DecodeHintType, any>, options?: IBrowserCodeReaderOptions);
}
+14
View File
@@ -0,0 +1,14 @@
import { QRCodeReader } from '@zxing/library';
import { BrowserCodeReader } from './BrowserCodeReader';
/**
* QR Code reader to use from browser.
*/
export class BrowserQRCodeReader extends BrowserCodeReader {
/**
* Creates an instance of BrowserQRCodeReader.
*/
constructor(hints, options) {
super(new QRCodeReader(), hints, options);
}
}
//# sourceMappingURL=BrowserQRCodeReader.js.map
@@ -0,0 +1 @@
{"version":3,"file":"BrowserQRCodeReader.js","sourceRoot":"","sources":["../../../src/readers/BrowserQRCodeReader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAGxD;;GAEG;AACH,MAAM,OAAO,mBAAoB,SAAQ,iBAAiB;IACxD;;OAEG;IACH,YACE,KAAgC,EAChC,OAAmC;QAEnC,KAAK,CAAC,IAAI,YAAY,EAAE,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;IAC5C,CAAC;CACF"}
@@ -0,0 +1,8 @@
export interface IBrowserCodeReaderOptions {
/** Delay time between subsequent successful decode results. */
delayBetweenScanSuccess?: number;
/** Delay time between decode attempts made by the scanner. */
delayBetweenScanAttempts?: number;
/** Timeout for waiting the video 'canplay' event. */
tryPlayVideoTimeout?: number;
}
@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=IBrowserCodeReaderOptions.js.map
@@ -0,0 +1 @@
{"version":3,"file":"IBrowserCodeReaderOptions.js","sourceRoot":"","sources":["../../../src/readers/IBrowserCodeReaderOptions.ts"],"names":[],"mappings":""}
+47
View File
@@ -0,0 +1,47 @@
import { EncodeHintType } from '@zxing/library';
declare abstract class BrowserCodeSvgWriter {
/**
* Default quiet zone in pixels.
*/
private static readonly QUIET_ZONE_SIZE;
/**
* SVG markup NameSpace
*/
private static readonly SVG_NS;
/**
* A HTML container element for the image.
*/
private containerElement;
/**
* Constructs. 😉
*/
constructor(containerElement: string | HTMLElement);
/**
* Writes the QR code to a SVG and renders it in the container.
*/
write(contents: string, width: number, height: number, hints?: Map<EncodeHintType, any>): SVGSVGElement;
/**
* Creates a SVG element.
*/
protected createSVGElement(w: number, h: number): SVGSVGElement;
/**
* Creates a SVG rect.
*/
protected createSvgPathPlaceholderElement(w: number, h: number): SVGPathElement;
/**
* Creates a SVG rect.
*/
protected createSvgRectElement(x: number, y: number, w: number, h: number): SVGRectElement;
/**
* Encodes the content to a Barcode type.
*/
private encode;
/**
* Renders the SVG in the container.
*
* @note the input matrix uses 0 == white, 1 == black. The output matrix
* uses 0 == black, 255 == white (i.e. an 8 bit greyscale bitmap).
*/
private renderResult;
}
export { BrowserCodeSvgWriter };
+131
View File
@@ -0,0 +1,131 @@
import { EncodeHintType, IllegalArgumentException, IllegalStateException, QRCodeDecoderErrorCorrectionLevel, QRCodeEncoder, } from '@zxing/library';
const svgNs = 'http://www.w3.org/2000/svg';
/**/
class BrowserCodeSvgWriter {
/**
* Constructs. 😉
*/
constructor(containerElement) {
if (typeof containerElement === 'string') {
const container = document.getElementById(containerElement);
if (!container) {
throw new Error(`Could not find a Container element with '${containerElement}'.`);
}
this.containerElement = container;
}
else {
this.containerElement = containerElement;
}
}
/**
* Writes the QR code to a SVG and renders it in the container.
*/
write(contents, width, height, hints) {
if (contents.length === 0) {
throw new IllegalArgumentException('Found empty contents');
}
if (width < 0 || height < 0) {
throw new IllegalArgumentException('Requested dimensions are too small: ' + width + 'x' + height);
}
const quietZone = hints && hints.get(EncodeHintType.MARGIN) !== undefined
? Number.parseInt(hints.get(EncodeHintType.MARGIN).toString(), 10)
: BrowserCodeSvgWriter.QUIET_ZONE_SIZE;
const code = this.encode(hints, contents);
return this.renderResult(code, width, height, quietZone);
}
/**
* Creates a SVG element.
*/
createSVGElement(w, h) {
const el = document.createElementNS(BrowserCodeSvgWriter.SVG_NS, 'svg');
el.setAttributeNS(svgNs, 'width', h.toString());
el.setAttributeNS(svgNs, 'height', w.toString());
return el;
}
/**
* Creates a SVG rect.
*/
createSvgPathPlaceholderElement(w, h) {
const el = document.createElementNS(BrowserCodeSvgWriter.SVG_NS, 'path');
el.setAttributeNS(svgNs, 'd', `M0 0h${w}v${h}H0z`);
el.setAttributeNS(svgNs, 'fill', 'none');
return el;
}
/**
* Creates a SVG rect.
*/
createSvgRectElement(x, y, w, h) {
const el = document.createElementNS(BrowserCodeSvgWriter.SVG_NS, 'rect');
el.setAttributeNS(svgNs, 'x', x.toString());
el.setAttributeNS(svgNs, 'y', y.toString());
el.setAttributeNS(svgNs, 'height', w.toString());
el.setAttributeNS(svgNs, 'width', h.toString());
el.setAttributeNS(svgNs, 'fill', '#000000');
return el;
}
/**
* Encodes the content to a Barcode type.
*/
encode(hints, contents) {
let errorCorrectionLevel = QRCodeDecoderErrorCorrectionLevel.L;
if (hints && hints.get(EncodeHintType.ERROR_CORRECTION) !== undefined) {
const correctionStr = hints.get(EncodeHintType.ERROR_CORRECTION).toString();
errorCorrectionLevel = QRCodeDecoderErrorCorrectionLevel.fromString(correctionStr);
}
const code = QRCodeEncoder.encode(contents, errorCorrectionLevel, hints);
return code;
}
/**
* Renders the SVG in the container.
*
* @note the input matrix uses 0 == white, 1 == black. The output matrix
* uses 0 == black, 255 == white (i.e. an 8 bit greyscale bitmap).
*/
renderResult(code, width /*int*/, height /*int*/, quietZone /*int*/) {
// if (this.format && format != this.format) {
// throw new IllegalArgumentException("Can only encode QR_CODE, but got " + format)
// }
const input = code.getMatrix();
if (input === null) {
throw new IllegalStateException();
}
const inputWidth = input.getWidth();
const inputHeight = input.getHeight();
const qrWidth = inputWidth + (quietZone * 2);
const qrHeight = inputHeight + (quietZone * 2);
const outputWidth = Math.max(width, qrWidth);
const outputHeight = Math.max(height, qrHeight);
const multiple = Math.min(Math.floor(outputWidth / qrWidth), Math.floor(outputHeight / qrHeight));
// Padding includes both the quiet zone and the extra white pixels to accommodate the requested
// dimensions. For example, if input is 25x25 the QR will be 33x33 including the quiet zone.
// If the requested size is 200x160, the multiple will be 4, for a QR of 132x132. These will
// handle all the padding from 100x100 (the actual QR) up to 200x160.
const leftPadding = Math.floor((outputWidth - (inputWidth * multiple)) / 2);
const topPadding = Math.floor((outputHeight - (inputHeight * multiple)) / 2);
const svgElement = this.createSVGElement(outputWidth, outputHeight);
const placeholder = this.createSvgPathPlaceholderElement(width, height);
svgElement.appendChild(placeholder);
this.containerElement.appendChild(svgElement);
// 2D loop
for (let inputY = 0, outputY = topPadding; inputY < inputHeight; inputY++, outputY += multiple) {
// Write the contents of this row of the barcode
for (let inputX = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) {
if (input.get(inputX, inputY) === 1) {
const svgRectElement = this.createSvgRectElement(outputX, outputY, multiple, multiple);
svgElement.appendChild(svgRectElement);
}
}
}
return svgElement;
}
}
/**
* Default quiet zone in pixels.
*/
BrowserCodeSvgWriter.QUIET_ZONE_SIZE = 4;
/**
* SVG markup NameSpace
*/
BrowserCodeSvgWriter.SVG_NS = 'http://www.w3.org/2000/svg';
export { BrowserCodeSvgWriter };
//# sourceMappingURL=BrowserCodeSvgWriter.js.map
@@ -0,0 +1 @@
{"version":3,"file":"BrowserCodeSvgWriter.js","sourceRoot":"","sources":["../../../src/writers/BrowserCodeSvgWriter.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,wBAAwB,EACxB,qBAAqB,EACrB,iCAAiC,EACjC,aAAa,GAEd,MAAM,gBAAgB,CAAC;AAExB,MAAM,KAAK,GAAG,4BAA4B,CAAC;AAE3C,IAAI;AACJ,MAAe,oBAAoB;IAiBjC;;OAEG;IACH,YAAmB,gBAAsC;QACvD,IAAI,OAAO,gBAAgB,KAAK,QAAQ,EAAE;YACxC,MAAM,SAAS,GAAG,QAAQ,CAAC,cAAc,CAAC,gBAAgB,CAAC,CAAC;YAC5D,IAAI,CAAC,SAAS,EAAE;gBAAE,MAAM,IAAI,KAAK,CAAC,4CAA4C,gBAAgB,IAAI,CAAC,CAAC;aAAE;YAEtG,IAAI,CAAC,gBAAgB,GAAG,SAAS,CAAC;SACnC;aAAM;YACL,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,CAAC;SAC1C;IACH,CAAC;IAED;;OAEG;IACI,KAAK,CACV,QAAgB,EAChB,KAAa,EACb,MAAc,EACd,KAAgC;QAGhC,IAAI,QAAQ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,CAAC,WAAW,GAAG,QAAQ,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;QAE7E,MAAM,UAAU,GAAG,IAAI,CAAC,gBAAgB,CAAC,WAAW,EAAE,YAAY,CAAC,CAAC;QAEpE,MAAM,WAAW,GAAG,IAAI,CAAC,+BAA+B,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAExE,UAAU,CAAC,WAAW,CAAC,WAAW,CAAC,CAAC;QAEpC,IAAI,CAAC,gBAAgB,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC;QAE9C,UAAU;QACV,KAAK,IAAI,MAAM,GAAG,CAAC,EAAE,OAAO,GAAG,UAAU,EAAE,MAAM,GAAG,WAAW,EAAE,MAAM,EAAE,EAAE,OAAO,IAAI,QAAQ,EAAE;YAC9F,gDAAgD;YAChD,KAAK,IAAI,MAAM,GAAG,CAAC,EAAE,OAAO,GAAG,WAAW,EAAE,MAAM,GAAG,UAAU,EAAE,MAAM,EAAE,EAAE,OAAO,IAAI,QAAQ,EAAE;gBAC9F,IAAI,KAAK,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE;oBACnC,MAAM,cAAc,GAAG,IAAI,CAAC,oBAAoB,CAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC;oBACvF,UAAU,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC;iBACxC;aACF;SACF;QAED,OAAO,UAAU,CAAC;IACpB,CAAC;;AA7KD;;GAEG;AACqB,oCAAe,GAAG,CAAC,CAAC;AAE5C;;GAEG;AACqB,2BAAM,GAAG,4BAA4B,CAAC;AAwKhE,OAAO,EAAE,oBAAoB,EAAE,CAAC"}
+39
View File
@@ -0,0 +1,39 @@
import { EncodeHintType } from '@zxing/library';
declare class BrowserQRCodeSvgWriter {
private static readonly QUIET_ZONE_SIZE;
/**
* Writes and renders a QRCode SVG element.
*
* @param contents
* @param width
* @param height
* @param hints
*/
write(contents: string, width: number, height: number, hints?: Map<EncodeHintType, any>): SVGSVGElement;
/**
* Renders the result and then appends it to the DOM.
*/
writeToDom(containerElement: string | HTMLElement, contents: string, width: number, height: number, hints?: Map<EncodeHintType, any>): void;
/**
* Note that the input matrix uses 0 == white, 1 == black.
* The output matrix uses 0 == black, 255 == white (i.e. an 8 bit greyscale bitmap).
*/
private renderResult;
/**
* Creates a SVG element.
*
* @param w SVG's width attribute
* @param h SVG's height attribute
*/
private createSVGElement;
/**
* Creates a SVG rect element.
*
* @param x Element's x coordinate
* @param y Element's y coordinate
* @param w Element's width attribute
* @param h Element's height attribute
*/
private createSvgRectElement;
}
export { BrowserQRCodeSvgWriter };
+122
View File
@@ -0,0 +1,122 @@
import { EncodeHintType, IllegalArgumentException, IllegalStateException, QRCodeDecoderErrorCorrectionLevel, QRCodeEncoder, } from '@zxing/library';
const svgNs = 'http://www.w3.org/2000/svg';
/**/
class BrowserQRCodeSvgWriter {
/**
* Writes and renders a QRCode SVG element.
*
* @param contents
* @param width
* @param height
* @param hints
*/
write(contents, width, height, hints) {
if (contents.length === 0) {
throw new IllegalArgumentException('Found empty contents');
}
// if (format != BarcodeFormat.QR_CODE) {
// throw new IllegalArgumentException("Can only encode QR_CODE, but got " + format)
// }
if (width < 0 || height < 0) {
throw new IllegalArgumentException('Requested dimensions are too small: ' + width + 'x' + height);
}
let errorCorrectionLevel = QRCodeDecoderErrorCorrectionLevel.L;
let quietZone = BrowserQRCodeSvgWriter.QUIET_ZONE_SIZE;
if (hints) {
if (undefined !== hints.get(EncodeHintType.ERROR_CORRECTION)) {
const correctionStr = hints.get(EncodeHintType.ERROR_CORRECTION).toString();
errorCorrectionLevel = QRCodeDecoderErrorCorrectionLevel.fromString(correctionStr);
}
if (undefined !== hints.get(EncodeHintType.MARGIN)) {
quietZone = Number.parseInt(hints.get(EncodeHintType.MARGIN).toString(), 10);
}
}
const code = QRCodeEncoder.encode(contents, errorCorrectionLevel, hints);
return this.renderResult(code, width, height, quietZone);
}
/**
* Renders the result and then appends it to the DOM.
*/
writeToDom(containerElement, contents, width, height, hints) {
if (typeof containerElement === 'string') {
const targetEl = document.querySelector(containerElement);
if (!targetEl) {
throw new Error('Could no find the target HTML element.');
}
containerElement = targetEl;
}
const svgElement = this.write(contents, width, height, hints);
if (containerElement instanceof HTMLElement) {
containerElement.appendChild(svgElement);
}
}
/**
* Note that the input matrix uses 0 == white, 1 == black.
* The output matrix uses 0 == black, 255 == white (i.e. an 8 bit greyscale bitmap).
*/
renderResult(code, width /*int*/, height /*int*/, quietZone /*int*/) {
const input = code.getMatrix();
if (input === null) {
throw new IllegalStateException();
}
const inputWidth = input.getWidth();
const inputHeight = input.getHeight();
const qrWidth = inputWidth + (quietZone * 2);
const qrHeight = inputHeight + (quietZone * 2);
const outputWidth = Math.max(width, qrWidth);
const outputHeight = Math.max(height, qrHeight);
const multiple = Math.min(Math.floor(outputWidth / qrWidth), Math.floor(outputHeight / qrHeight));
// Padding includes both the quiet zone and the extra white pixels to accommodate the requested
// dimensions. For example, if input is 25x25 the QR will be 33x33 including the quiet zone.
// If the requested size is 200x160, the multiple will be 4, for a QR of 132x132. These will
// handle all the padding from 100x100 (the actual QR) up to 200x160.
const leftPadding = Math.floor((outputWidth - (inputWidth * multiple)) / 2);
const topPadding = Math.floor((outputHeight - (inputHeight * multiple)) / 2);
const svgElement = this.createSVGElement(outputWidth, outputHeight);
for (let inputY = 0, outputY = topPadding; inputY < inputHeight; inputY++, outputY += multiple) {
// Write the contents of this row of the barcode
for (let inputX = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) {
if (input.get(inputX, inputY) === 1) {
const svgRectElement = this.createSvgRectElement(outputX, outputY, multiple, multiple);
svgElement.appendChild(svgRectElement);
}
}
}
return svgElement;
}
/**
* Creates a SVG element.
*
* @param w SVG's width attribute
* @param h SVG's height attribute
*/
createSVGElement(w, h) {
const svgElement = document.createElementNS(svgNs, 'svg');
const width = w.toString();
const height = h.toString();
svgElement.setAttribute('height', height);
svgElement.setAttribute('width', width);
svgElement.setAttribute('viewBox', "0 0 " + width + " " + height);
return svgElement;
}
/**
* Creates a SVG rect element.
*
* @param x Element's x coordinate
* @param y Element's y coordinate
* @param w Element's width attribute
* @param h Element's height attribute
*/
createSvgRectElement(x, y, w, h) {
const rect = document.createElementNS(svgNs, 'rect');
rect.setAttribute('x', x.toString());
rect.setAttribute('y', y.toString());
rect.setAttribute('height', w.toString());
rect.setAttribute('width', h.toString());
rect.setAttribute('fill', '#000000');
return rect;
}
}
BrowserQRCodeSvgWriter.QUIET_ZONE_SIZE = 4;
export { BrowserQRCodeSvgWriter };
//# sourceMappingURL=BrowserQRCodeSvgWriter.js.map
@@ -0,0 +1 @@
{"version":3,"file":"BrowserQRCodeSvgWriter.js","sourceRoot":"","sources":["../../../src/writers/BrowserQRCodeSvgWriter.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,wBAAwB,EACxB,qBAAqB,EACrB,iCAAiC,EACjC,aAAa,GAEd,MAAM,gBAAgB,CAAC;AAExB,MAAM,KAAK,GAAG,4BAA4B,CAAC;AAE3C,IAAI;AACJ,MAAM,sBAAsB;IAI1B;;;;;;;OAOG;IACI,KAAK,CACV,QAAgB,EAChB,KAAa,EACb,MAAc,EACd,KAAgC;QAGhC,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE;YACzB,MAAM,IAAI,wBAAwB,CAAC,sBAAsB,CAAC,CAAC;SAC5D;QAED,yCAAyC;QACzC,qFAAqF;QACrF,IAAI;QAEJ,IAAI,KAAK,GAAG,CAAC,IAAI,MAAM,GAAG,CAAC,EAAE;YAC3B,MAAM,IAAI,wBAAwB,CAAC,sCAAsC,GAAG,KAAK,GAAG,GAAG,GAAG,MAAM,CAAC,CAAC;SACnG;QAED,IAAI,oBAAoB,GAAG,iCAAiC,CAAC,CAAC,CAAC;QAC/D,IAAI,SAAS,GAAG,sBAAsB,CAAC,eAAe,CAAC;QAEvD,IAAI,KAAK,EAAE;YAET,IAAI,SAA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