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
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 ZXing for JS
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+197
View File
@@ -0,0 +1,197 @@
[<img align="right" src="https://raw.github.com/wiki/zxing/zxing/zxing-logo.png"/>][1]
# ZXing
## What is ZXing?
> [ZXing][1] ("zebra crossing") is an open-source, multi-format 1D/2D barcode image processing library implemented in Java, with ports to other languages.
## Browser layer
This is a library for enabling you to use with ease the ZXing for JS library on the browser. It includes features like scanning an `<img>` element, as well as `<video>`, images and videos from URLs and also it helps handling webcam use for scanning directly from a hardware connected camera. It does not offers support to any physical barcode readers or things like that.
See @zxing-js/library for the complete API including decoding classes and use outside of the browser.
See @zxing-js/ngx-scanner for using the library in Angular.
See @zxing-js/text-encoding for special character support in barcodes.
## Usage (how to use)
Installation, import into app and usage examples in this section.
### Instalation
Install via yarn, npm, etc:
```bash
yarn add @zxing/browser
```
```bash
npm i @zxing/browser
```
Or just import an script tag from your favorite NPM registry connected CDN:
```html
<!-- loading ZXingBrowser via UNPKG -->
<script type="text/javascript" src="https://unpkg.com/@zxing/browser@latest"></script>
```
### How to import into your app
#### ES6 modules
```html
<script type="module">
import { BrowserQRCodeReader } from '@zxing/browser';
const codeReader = new BrowserQRCodeReader();
// do something with codeReader...
</script>
```
##### Or asynchronously
```html
<script type="module">
import('@zxing/browser').then({ BrowserQRCodeReader } => {
const codeReader = new BrowserQRCodeReader();
// do something with codeReader...
});
</script>
```
#### With AMD
```html
<script type="text/javascript" src="https://unpkg.com/requirejs"></script>
<script type="text/javascript">
require(['@zxing/browser'], ZXingBrowser => {
const codeReader = new ZXingBrowser.BrowserQRCodeReader();
// do something with codeReader...
});
</script>
```
#### With UMD
```html
<script type="text/javascript" src="https://unpkg.com/@zxing/browser@latest"></script>
<script type="text/javascript">
window.addEventListener('load', () => {
const codeReader = new ZXingBrowser.BrowserQRCodeReader();
// do something with codeReader...
});
</script>
```
### Using the API
Examples here will assume you already imported ZXingBrowser into your app.
#### Scan from webcam
Continuous scan (runs and decodes barcodes until you stop it):
```typescript
const codeReader = new BrowserQRCodeReader();
const videoInputDevices = await ZXingBrowser.BrowserCodeReader.listVideoInputDevices();
// choose your media device (webcam, frontal camera, back camera, etc.)
const selectedDeviceId = videoInputDevices[0].deviceId;
console.log(`Started decode from camera with id ${selectedDeviceId}`);
const previewElem = document.querySelector('#test-area-qr-code-webcam > video');
// you can use the controls to stop() the scan or switchTorch() if available
const controls = await codeReader.decodeFromVideoDevice(selectedDeviceId, previewElem, (result, error, controls) => {
// use the result and error values to choose your actions
// you can also use controls API in this scope like the controls
// returned from the method.
});
// stops scanning after 20 seconds
setTimeout(() => controls.stop(), 20000);
```
You can also use `decodeFromConstraints` instead of `decodeFromVideoDevice` to pass your own constraints for the method choose the device you want directly from your constraints.
Also, `decodeOnceFromVideoDevice` is available too so you can `await` the method until it detects the first barcode.
### Scan from video or image URL
```javascript
const codeReader = new ZXingBrowser.BrowserQRCodeReader();
const source = 'https://my-image-or-video/01.png';
const resultImage = await codeReader.decodeFromImageUrl(source);
// or use decodeFromVideoUrl for videos
const resultVideo = await codeReader.decodeFromVideoUrl(source);
```
### Scan from video or image HTML element
```javascript
const codeReader = new ZXingBrowser.BrowserQRCodeReader();
const sourceElem = document.querySelector('#my-image-id');
const resultImage = await codeReader.decodeFromImageElement(sourceElem);
// or use decodeFromVideoElement for videos
const resultVideo = await codeReader.decodeFromVideoElement(sourceElem);
```
### Other scan methods
There's still other scan methods you can use for decoding barcodes in the browser with `BrowserCodeReader` family, all of those and previous listed in here:
- `decodeFromCanvas`
- `decodeFromImageElement`
- `decodeFromImageUrl`
- `decodeFromConstraints`
- `decodeFromStream`
- `decodeFromVideoDevice`
- `decodeFromVideoElement`
- `decodeFromVideoUrl`
- `decodeOnceFromConstraints`
- `decodeOnceFromStream`
- `decodeOnceFromVideoDevice`
- `decodeOnceFromVideoElement`
- `decodeOnceFromVideoUrl`
That's it for now.
### List of browser readers
- `BrowserAztecCodeReader`
- `BrowserCodeReader` (abstract, needs to be extend for use)
- `BrowserDatamatrixCodeReader`
- `BrowserMultiFormatOneDReader`
- `BrowserMultiFormatReader` (2D + 1D)
- `BrowserPDF417CodeReader`
- `BrowserQRCodeReader`
### Customize `BrowserCodeReader` options
You can also customize some options on the code reader at instantiation time. More docs comming soon.
---
[![Bless](https://cdn.rawgit.com/LunaGao/BlessYourCodeTag/master/tags/alpaca.svg)](http://lunagao.github.io/BlessYourCodeTag/)
[0]: https://www.npmjs.com/package/@zxing/browser
[1]: https://github.com/zxing/zxing
@@ -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;
+3
View File
@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# 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,154 @@
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.HTMLCanvasElementLuminanceSource = void 0;
var library_1 = require("@zxing/library");
/**/
var HTMLCanvasElementLuminanceSource = /** @class */ (function (_super) {
__extends(HTMLCanvasElementLuminanceSource, _super);
function HTMLCanvasElementLuminanceSource(canvas) {
var _this = _super.call(this, canvas.width, canvas.height) || this;
_this.canvas = canvas;
_this.tempCanvasElement = null;
_this.buffer = HTMLCanvasElementLuminanceSource.makeBufferFromCanvasImageData(canvas);
return _this;
}
HTMLCanvasElementLuminanceSource.makeBufferFromCanvasImageData = function (canvas) {
var canvasCtx;
try {
canvasCtx = canvas.getContext('2d', { willReadFrequently: true });
}
catch (e) {
canvasCtx = canvas.getContext('2d');
}
if (!canvasCtx) {
throw new Error('Couldn\'t get canvas context.');
}
var imageData = canvasCtx.getImageData(0, 0, canvas.width, canvas.height);
return HTMLCanvasElementLuminanceSource.toGrayscaleBuffer(imageData.data, canvas.width, canvas.height);
};
HTMLCanvasElementLuminanceSource.toGrayscaleBuffer = function (imageBuffer, width, height) {
var grayscaleBuffer = new Uint8ClampedArray(width * height);
for (var i = 0, j = 0, length_1 = imageBuffer.length; i < length_1; i += 4, j++) {
var gray = void 0;
var 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 {
var pixelR = imageBuffer[i];
var pixelG = imageBuffer[i + 1];
var 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;
};
HTMLCanvasElementLuminanceSource.prototype.getRow = function (y /*int*/, row) {
if (y < 0 || y >= this.getHeight()) {
throw new library_1.IllegalArgumentException('Requested row is outside the image: ' + y);
}
var width = this.getWidth();
var 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;
};
HTMLCanvasElementLuminanceSource.prototype.getMatrix = function () {
return this.buffer;
};
HTMLCanvasElementLuminanceSource.prototype.isCropSupported = function () {
return true;
};
HTMLCanvasElementLuminanceSource.prototype.crop = function (left /*int*/, top /*int*/, width /*int*/, height /*int*/) {
_super.prototype.crop.call(this, left, top, width, height);
return this;
};
/**
* This is always true, since the image is a gray-scale image.
*
* @return true
*/
HTMLCanvasElementLuminanceSource.prototype.isRotateSupported = function () {
return true;
};
HTMLCanvasElementLuminanceSource.prototype.rotateCounterClockwise = function () {
this.rotate(-90);
return this;
};
HTMLCanvasElementLuminanceSource.prototype.rotateCounterClockwise45 = function () {
this.rotate(-45);
return this;
};
HTMLCanvasElementLuminanceSource.prototype.invert = function () {
return new library_1.InvertedLuminanceSource(this);
};
HTMLCanvasElementLuminanceSource.prototype.getTempCanvasElement = function () {
if (null === this.tempCanvasElement) {
var tempCanvasElement = this.canvas.ownerDocument.createElement('canvas');
tempCanvasElement.width = this.canvas.width;
tempCanvasElement.height = this.canvas.height;
this.tempCanvasElement = tempCanvasElement;
}
return this.tempCanvasElement;
};
HTMLCanvasElementLuminanceSource.prototype.rotate = function (angle) {
var tempCanvasElement = this.getTempCanvasElement();
if (!tempCanvasElement) {
throw new Error('Could not create a Canvas element.');
}
var angleRadians = angle * HTMLCanvasElementLuminanceSource.DEGREE_TO_RADIANS;
// Calculate and set new dimensions for temp canvas
var width = this.canvas.width;
var height = this.canvas.height;
var newWidth = Math.ceil(Math.abs(Math.cos(angleRadians)) * width + Math.abs(Math.sin(angleRadians)) * height);
var newHeight = Math.ceil(Math.abs(Math.sin(angleRadians)) * width + Math.abs(Math.cos(angleRadians)) * height);
tempCanvasElement.width = newWidth;
tempCanvasElement.height = newHeight;
var 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;
return HTMLCanvasElementLuminanceSource;
}(library_1.LuminanceSource));
exports.HTMLCanvasElementLuminanceSource = HTMLCanvasElementLuminanceSource;
//# sourceMappingURL=HTMLCanvasElementLuminanceSource.js.map
@@ -0,0 +1 @@
{"version":3,"file":"HTMLCanvasElementLuminanceSource.js","sourceRoot":"","sources":["../../../src/common/HTMLCanvasElementLuminanceSource.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,0CAIwB;AAExB,IAAI;AACJ;IAAsD,oDAAe;IA+CnE,0CAA2B,MAAyB;QAApD,YACE,kBAAM,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC,SAEnC;QAH0B,YAAM,GAAN,MAAM,CAAmB;QAF5C,uBAAiB,GAAuB,IAAI,CAAC;QAInD,KAAI,CAAC,MAAM,GAAG,gCAAgC,CAAC,6BAA6B,CAAC,MAAM,CAAC,CAAC;;IACvF,CAAC;IA9Cc,8DAA6B,GAA5C,UAA6C,MAAyB;QACpE,IAAI,SAAS,CAAC;QAEd,IAAI;YACF,SAAS,GAAG,MAAM,CAAC,UAAU,CAAC,IAAI,EAAE,EAAE,kBAAkB,EAAE,IAAI,EAAE,CAAC,CAAC;SACnE;QAAC,OAAO,CAAC,EAAE;YACV,SAAS,GAAG,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;SACrC;QAED,IAAI,CAAC,SAAS,EAAE;YAAE,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;SAAE;QACrE,IAAM,SAAS,GAAG,SAAS,CAAC,YAAY,CAAC,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;QAC5E,OAAO,gCAAgC,CAAC,iBAAi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AC,GAAG,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC,GAAG,MAAM,CACrF,CAAC;QACF,iBAAiB,CAAC,KAAK,GAAG,QAAQ,CAAC;QACnC,iBAAiB,CAAC,MAAM,GAAG,SAAS,CAAC;QAErC,IAAM,WAAW,GAAG,iBAAiB,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;QACvD,IAAI,CAAC,WAAW,EAAE;YAAE,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;SAAE;QAEpF,kEAAkE;QAClE,WAAW,CAAC,SAAS,CAAC,QAAQ,GAAG,CAAC,EAAE,SAAS,GAAG,CAAC,CAAC,CAAC;QACnD,WAAW,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC;QACjC,WAAW,CAAC,SAAS,CAAC,IAAI,CAAC,MAAM,EAAE,KAAK,GAAG,CAAC,CAAC,EAAE,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC;QAC5D,IAAI,CAAC,MAAM,GAAG,gCAAgC,CAAC,6BAA6B,CAAC,iBAAiB,CAAC,CAAC;QAChG,OAAO,IAAI,CAAC;IACd,CAAC;IApJc,kDAAiB,GAAG,IAAI,CAAC,EAAE,GAAG,GAAG,CAAC;IAqJnD,uCAAC;CAAA,AAvJD,CAAsD,yBAAe,GAuJpE;AAvJY,4EAAgC"}
+4
View File
@@ -0,0 +1,4 @@
/**
* HTML elements that can be decoded.
*/
export declare type HTMLVisualMediaElement = HTMLVideoElement | HTMLImageElement;
+3
View File
@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=HTMLVisualMediaElement.js.map
+1
View File
@@ -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;
}
+3
View File
@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# 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;
+24
View File
@@ -0,0 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.canEnumerateDevices = exports.hasNavigator = void 0;
/**
* If navigator is present.
*/
function hasNavigator() {
return typeof navigator !== 'undefined';
}
exports.hasNavigator = hasNavigator;
/**
* If mediaDevices under navigator is supported.
*/
function isMediaDevicesSupported() {
return hasNavigator() && !!navigator.mediaDevices;
}
/**
* If enumerateDevices under navigator is supported.
*/
function canEnumerateDevices() {
return !!(isMediaDevicesSupported() && navigator.mediaDevices.enumerateDevices);
}
exports.canEnumerateDevices = canEnumerateDevices;
//# 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,SAAgB,YAAY;IAC1B,OAAO,OAAO,SAAS,KAAK,WAAW,CAAC;AAC1C,CAAC;AAFD,oCAEC;AACD;;GAEG;AACH,SAAS,uBAAuB;IAC9B,OAAO,YAAY,EAAE,IAAI,CAAC,CAAC,SAAS,CAAC,YAAY,CAAC;AACpD,CAAC;AACD;;GAEG;AACH,SAAgB,mBAAmB;IACjC,OAAO,CAAC,CAAC,CAAC,uBAAuB,EAAE,IAAI,SAAS,CAAC,YAAY,CAAC,gBAAgB,CAAC,CAAC;AAClF,CAAC;AAFD,kDAEC"}
+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';
+34
View File
@@ -0,0 +1,34 @@
"use strict";
// public API
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BarcodeFormat = void 0;
// core
var library_1 = require("@zxing/library");
Object.defineProperty(exports, "BarcodeFormat", { enumerable: true, get: function () { return library_1.BarcodeFormat; } });
// common
__exportStar(require("./common/HTMLCanvasElementLuminanceSource"), exports);
__exportStar(require("./common/HTMLVisualMediaElement"), exports);
__exportStar(require("./common/IScannerControls"), exports);
// readers
__exportStar(require("./readers/BrowserAztecCodeReader"), exports);
__exportStar(require("./readers/BrowserMultiFormatOneDReader"), exports);
__exportStar(require("./readers/BrowserCodeReader"), exports);
__exportStar(require("./readers/BrowserDatamatrixCodeReader"), exports);
__exportStar(require("./readers/BrowserMultiFormatReader"), exports);
__exportStar(require("./readers/BrowserPDF417Reader"), exports);
__exportStar(require("./readers/BrowserQRCodeReader"), exports);
__exportStar(require("./readers/IBrowserCodeReaderOptions"), exports);
// writers
__exportStar(require("./writers/BrowserCodeSvgWriter"), exports);
__exportStar(require("./writers/BrowserQRCodeSvgWriter"), exports);
//# 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,0CAA+C;AAAtC,wGAAA,aAAa,OAAA;AAEtB,SAAS;AACT,4EAA0D;AAC1D,kEAAgD;AAChD,4DAA0C;AAE1C,UAAU;AACV,mEAAiD;AACjD,yEAAuD;AACvD,8DAA4C;AAC5C,wEAAsD;AACtD,qEAAmD;AACnD,gEAA8C;AAC9C,gEAA8C;AAC9C,sEAAoD;AAEpD,UAAU;AACV,iEAA+C;AAC/C,mEAAiD"}
+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);
}
+38
View File
@@ -0,0 +1,38 @@
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.BrowserAztecCodeReader = void 0;
var library_1 = require("@zxing/library");
var BrowserCodeReader_1 = require("./BrowserCodeReader");
/**
* Aztec Code reader to use from browser.
*
* @class BrowserAztecCodeReader
* @extends {BrowserCodeReader}
*/
var BrowserAztecCodeReader = /** @class */ (function (_super) {
__extends(BrowserAztecCodeReader, _super);
/**
* Creates an instance of BrowserAztecCodeReader.
*/
function BrowserAztecCodeReader(hints, options) {
return _super.call(this, new library_1.AztecCodeReader(), hints, options) || this;
}
return BrowserAztecCodeReader;
}(BrowserCodeReader_1.BrowserCodeReader));
exports.BrowserAztecCodeReader = BrowserAztecCodeReader;
//# sourceMappingURL=BrowserAztecCodeReader.js.map
@@ -0,0 +1 @@
{"version":3,"file":"BrowserAztecCodeReader.js","sourceRoot":"","sources":["../../../src/readers/BrowserAztecCodeReader.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,0CAAiE;AACjE,yDAAwD;AAGxD;;;;;GAKG;AACH;IAA4C,0CAAiB;IAC3D;;OAEG;IACH,gCACE,KAAgC,EAChC,OAAmC;eAEnC,kBAAM,IAAI,yBAAe,EAAE,EAAE,KAAK,EAAE,OAAO,CAAC;IAC9C,CAAC;IACH,6BAAC;AAAD,CAAC,AAVD,CAA4C,qCAAiB,GAU5D;AAVY,wDAAsB"}
+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;
}
File diff suppressed because it is too large Load Diff
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);
}
+35
View File
@@ -0,0 +1,35 @@
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.BrowserDatamatrixCodeReader = void 0;
var library_1 = require("@zxing/library");
var BrowserCodeReader_1 = require("./BrowserCodeReader");
/**
* QR Code reader to use from browser.
*/
var BrowserDatamatrixCodeReader = /** @class */ (function (_super) {
__extends(BrowserDatamatrixCodeReader, _super);
/**
* Creates an instance of BrowserQRCodeReader.
*/
function BrowserDatamatrixCodeReader(hints, options) {
return _super.call(this, new library_1.DataMatrixReader(), hints, options) || this;
}
return BrowserDatamatrixCodeReader;
}(BrowserCodeReader_1.BrowserCodeReader));
exports.BrowserDatamatrixCodeReader = BrowserDatamatrixCodeReader;
//# sourceMappingURL=BrowserDatamatrixCodeReader.js.map
@@ -0,0 +1 @@
{"version":3,"file":"BrowserDatamatrixCodeReader.js","sourceRoot":"","sources":["../../../src/readers/BrowserDatamatrixCodeReader.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,0CAAkE;AAClE,yDAAwD;AAGxD;;GAEG;AACH;IAAiD,+CAAiB;IAChE;;OAEG;IACH,qCACE,KAAgC,EAChC,OAAmC;eAEnC,kBAAM,IAAI,0BAAgB,EAAE,EAAE,KAAK,EAAE,OAAO,CAAC;IAC/C,CAAC;IACH,kCAAC;AAAD,CAAC,AAVD,CAAiD,qCAAiB,GAUjE;AAVY,kEAA2B"}
@@ -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,37 @@
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.BrowserMultiFormatOneDReader = void 0;
var library_1 = require("@zxing/library");
var BrowserCodeReader_1 = require("./BrowserCodeReader");
/**
* Reader to be used for any One Dimension type barcode.
*/
var BrowserMultiFormatOneDReader = /** @class */ (function (_super) {
__extends(BrowserMultiFormatOneDReader, _super);
/**
* Creates an instance of BrowserBarcodeReader.
* @param {Map<DecodeHintType, any>} hints?
* @param options
*/
function BrowserMultiFormatOneDReader(hints, options) {
return _super.call(this, new library_1.MultiFormatOneDReader(hints), hints, options) || this;
}
return BrowserMultiFormatOneDReader;
}(BrowserCodeReader_1.BrowserCodeReader));
exports.BrowserMultiFormatOneDReader = BrowserMultiFormatOneDReader;
//# sourceMappingURL=BrowserMultiFormatOneDReader.js.map
@@ -0,0 +1 @@
{"version":3,"file":"BrowserMultiFormatOneDReader.js","sourceRoot":"","sources":["../../../src/readers/BrowserMultiFormatOneDReader.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,0CAAuE;AACvE,yDAAwD;AAGxD;;GAEG;AACH;IAAkD,gDAAiB;IACjE;;;;OAIG;IACH,sCAAmB,KAAgC,EAAE,OAAmC;eACtF,kBAAM,IAAI,+BAAqB,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC;IACzD,CAAC;IACH,mCAAC;AAAD,CAAC,AATD,CAAkD,qCAAiB,GASlE;AATY,oEAA4B"}
+17
View File
@@ -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;
}
+56
View File
@@ -0,0 +1,56 @@
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.BrowserMultiFormatReader = void 0;
var library_1 = require("@zxing/library");
var BrowserCodeReader_1 = require("./BrowserCodeReader");
var BrowserMultiFormatReader = /** @class */ (function (_super) {
__extends(BrowserMultiFormatReader, _super);
function BrowserMultiFormatReader(hints, options) {
var _this = this;
var reader = new library_1.MultiFormatReader();
reader.setHints(hints);
_this = _super.call(this, reader, hints, options) || this;
_this.reader = reader;
return _this;
}
Object.defineProperty(BrowserMultiFormatReader.prototype, "possibleFormats", {
set: function (formats) {
this.hints.set(library_1.DecodeHintType.POSSIBLE_FORMATS, formats);
this.reader.setHints(this.hints);
},
enumerable: false,
configurable: true
});
/**
* Overwrite decodeBitmap to call decodeWithState, which will pay
* attention to the hints set in the constructor function
*/
BrowserMultiFormatReader.prototype.decodeBitmap = function (binaryBitmap) {
return this.reader.decodeWithState(binaryBitmap);
};
/**
* Allows to change hints in runtime.
*/
BrowserMultiFormatReader.prototype.setHints = function (hints) {
this.hints = hints;
this.reader.setHints(this.hints);
};
return BrowserMultiFormatReader;
}(BrowserCodeReader_1.BrowserCodeReader));
exports.BrowserMultiFormatReader = BrowserMultiFormatReader;
//# sourceMappingURL=BrowserMultiFormatReader.js.map
@@ -0,0 +1 @@
{"version":3,"file":"BrowserMultiFormatReader.js","sourceRoot":"","sources":["../../../src/readers/BrowserMultiFormatReader.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,0CAMwB;AACxB,yDAAwD;AAGxD;IAA8C,4CAAiB;IAS7D,kCACE,KAAgC,EAChC,OAAmC;QAFrC,iBAQC;QAJC,IAAM,MAAM,GAAG,IAAI,2BAAiB,EAAE,CAAC;QACvC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;QACvB,QAAA,kBAAM,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,SAAC;QAC9B,KAAI,CAAC,MAAM,GAAG,MAAM,CAAC;;IACvB,CAAC;IAfD,sBAAI,qDAAe;aAAnB,UAAoB,OAAwB;YAC1C,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,wBAAc,CAAC,gBAAgB,EAAE,OAAO,CAAC,CAAC;YACzD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACnC,CAAC;;;OAAA;IAcD;;;OAGG;IACI,+CAAY,GAAnB,UAAoB,YAA0B;QAC5C,OAAO,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,YAAY,CAAC,CAAC;IACnD,CAAC;IAED;;OAEG;IACI,2CAAQ,GAAf,UAAgB,KAA+B;QAC7C,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACnC,CAAC;IACH,+BAAC;AAAD,CAAC,AAlCD,CAA8C,qCAAiB,GAkC9D;AAlCY,4DAAwB"}
+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);
}
+35
View File
@@ -0,0 +1,35 @@
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.BrowserPDF417Reader = void 0;
var library_1 = require("@zxing/library");
var BrowserCodeReader_1 = require("./BrowserCodeReader");
/**
* QR Code reader to use from browser.
*/
var BrowserPDF417Reader = /** @class */ (function (_super) {
__extends(BrowserPDF417Reader, _super);
/**
* Creates an instance of BrowserPDF417Reader.
*/
function BrowserPDF417Reader(hints, options) {
return _super.call(this, new library_1.PDF417Reader(), hints, options) || this;
}
return BrowserPDF417Reader;
}(BrowserCodeReader_1.BrowserCodeReader));
exports.BrowserPDF417Reader = BrowserPDF417Reader;
//# sourceMappingURL=BrowserPDF417Reader.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"BrowserPDF417Reader.js","sourceRoot":"","sources":["../../../src/readers/BrowserPDF417Reader.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,0CAA8D;AAC9D,yDAAwD;AAGxD;;GAEG;AACH;IAAyC,uCAAiB;IACxD;;OAEG;IACH,6BACE,KAAgC,EAChC,OAAmC;eAEnC,kBAAM,IAAI,sBAAY,EAAE,EAAE,KAAK,EAAE,OAAO,CAAC;IAC3C,CAAC;IACH,0BAAC;AAAD,CAAC,AAVD,CAAyC,qCAAiB,GAUzD;AAVY,kDAAmB"}
+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);
}
+35
View File
@@ -0,0 +1,35 @@
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.BrowserQRCodeReader = void 0;
var library_1 = require("@zxing/library");
var BrowserCodeReader_1 = require("./BrowserCodeReader");
/**
* QR Code reader to use from browser.
*/
var BrowserQRCodeReader = /** @class */ (function (_super) {
__extends(BrowserQRCodeReader, _super);
/**
* Creates an instance of BrowserQRCodeReader.
*/
function BrowserQRCodeReader(hints, options) {
return _super.call(this, new library_1.QRCodeReader(), hints, options) || this;
}
return BrowserQRCodeReader;
}(BrowserCodeReader_1.BrowserCodeReader));
exports.BrowserQRCodeReader = BrowserQRCodeReader;
//# sourceMappingURL=BrowserQRCodeReader.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"BrowserQRCodeReader.js","sourceRoot":"","sources":["../../../src/readers/BrowserQRCodeReader.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,0CAA8D;AAC9D,yDAAwD;AAGxD;;GAEG;AACH;IAAyC,uCAAiB;IACxD;;OAEG;IACH,6BACE,KAAgC,EAChC,OAAmC;eAEnC,kBAAM,IAAI,sBAAY,EAAE,EAAE,KAAK,EAAE,OAAO,CAAC;IAC3C,CAAC;IACH,0BAAC;AAAD,CAAC,AAVD,CAAyC,qCAAiB,GAUzD;AAVY,kDAAmB"}
@@ -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;
}
+3
View File
@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# 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 };
+135
View File
@@ -0,0 +1,135 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BrowserCodeSvgWriter = void 0;
var library_1 = require("@zxing/library");
var svgNs = 'http://www.w3.org/2000/svg';
/**/
var BrowserCodeSvgWriter = /** @class */ (function () {
/**
* Constructs. 😉
*/
function BrowserCodeSvgWriter(containerElement) {
if (typeof containerElement === 'string') {
var container = document.getElementById(containerElement);
if (!container) {
throw new Error("Could not find a Container element with '".concat(containerElement, "'."));
}
this.containerElement = container;
}
else {
this.containerElement = containerElement;
}
}
/**
* Writes the QR code to a SVG and renders it in the container.
*/
BrowserCodeSvgWriter.prototype.write = function (contents, width, height, hints) {
if (contents.length === 0) {
throw new library_1.IllegalArgumentException('Found empty contents');
}
if (width < 0 || height < 0) {
throw new library_1.IllegalArgumentException('Requested dimensions are too small: ' + width + 'x' + height);
}
var quietZone = hints && hints.get(library_1.EncodeHintType.MARGIN) !== undefined
? Number.parseInt(hints.get(library_1.EncodeHintType.MARGIN).toString(), 10)
: BrowserCodeSvgWriter.QUIET_ZONE_SIZE;
var code = this.encode(hints, contents);
return this.renderResult(code, width, height, quietZone);
};
/**
* Creates a SVG element.
*/
BrowserCodeSvgWriter.prototype.createSVGElement = function (w, h) {
var 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.
*/
BrowserCodeSvgWriter.prototype.createSvgPathPlaceholderElement = function (w, h) {
var el = document.createElementNS(BrowserCodeSvgWriter.SVG_NS, 'path');
el.setAttributeNS(svgNs, 'd', "M0 0h".concat(w, "v").concat(h, "H0z"));
el.setAttributeNS(svgNs, 'fill', 'none');
return el;
};
/**
* Creates a SVG rect.
*/
BrowserCodeSvgWriter.prototype.createSvgRectElement = function (x, y, w, h) {
var 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.
*/
BrowserCodeSvgWriter.prototype.encode = function (hints, contents) {
var errorCorrectionLevel = library_1.QRCodeDecoderErrorCorrectionLevel.L;
if (hints && hints.get(library_1.EncodeHintType.ERROR_CORRECTION) !== undefined) {
var correctionStr = hints.get(library_1.EncodeHintType.ERROR_CORRECTION).toString();
errorCorrectionLevel = library_1.QRCodeDecoderErrorCorrectionLevel.fromString(correctionStr);
}
var code = library_1.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).
*/
BrowserCodeSvgWriter.prototype.renderResult = function (code, width /*int*/, height /*int*/, quietZone /*int*/) {
// if (this.format && format != this.format) {
// throw new IllegalArgumentException("Can only encode QR_CODE, but got " + format)
// }
var input = code.getMatrix();
if (input === null) {
throw new library_1.IllegalStateException();
}
var inputWidth = input.getWidth();
var inputHeight = input.getHeight();
var qrWidth = inputWidth + (quietZone * 2);
var qrHeight = inputHeight + (quietZone * 2);
var outputWidth = Math.max(width, qrWidth);
var outputHeight = Math.max(height, qrHeight);
var 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.
var leftPadding = Math.floor((outputWidth - (inputWidth * multiple)) / 2);
var topPadding = Math.floor((outputHeight - (inputHeight * multiple)) / 2);
var svgElement = this.createSVGElement(outputWidth, outputHeight);
var placeholder = this.createSvgPathPlaceholderElement(width, height);
svgElement.appendChild(placeholder);
this.containerElement.appendChild(svgElement);
// 2D loop
for (var inputY = 0, outputY = topPadding; inputY < inputHeight; inputY++, outputY += multiple) {
// Write the contents of this row of the barcode
for (var inputX = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) {
if (input.get(inputX, inputY) === 1) {
var 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';
return BrowserCodeSvgWriter;
}());
exports.BrowserCodeSvgWriter = BrowserCodeSvgWriter;
//# sourceMappingURL=BrowserCodeSvgWriter.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"BrowserCodeSvgWriter.js","sourceRoot":"","sources":["../../../src/writers/BrowserCodeSvgWriter.ts"],"names":[],"mappings":";;;AAAA,0CAOwB;AAExB,IAAM,KAAK,GAAG,4BAA4B,CAAC;AAE3C,IAAI;AACJ;IAiBE;;OAEG;IACH,8BAAmB,gBAAsC;QACvD,IAAI,OAAO,gBAAgB,KAAK,QAAQ,EAAE;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EAAE,QAAQ,CAAC,CAAC;oBACvF,UAAU,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC;iBACxC;aACF;SACF;QAED,OAAO,UAAU,CAAC;IACpB,CAAC;IA7KD;;OAEG;IACqB,oCAAe,GAAG,CAAC,CAAC;IAE5C;;OAEG;IACqB,2BAAM,GAAG,4BAA4B,CAAC;IAsKhE,2BAAC;CAAA,AAhLD,IAgLC;AAEQ,oDAAoB"}
+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 };
+128
View File
@@ -0,0 +1,128 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BrowserQRCodeSvgWriter = void 0;
var library_1 = require("@zxing/library");
var svgNs = 'http://www.w3.org/2000/svg';
/**/
var BrowserQRCodeSvgWriter = /** @class */ (function () {
function BrowserQRCodeSvgWriter() {
}
/**
* Writes and renders a QRCode SVG element.
*
* @param contents
* @param width
* @param height
* @param hints
*/
BrowserQRCodeSvgWriter.prototype.write = function (contents, width, height, hints) {
if (contents.length === 0) {
throw new library_1.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 library_1.IllegalArgumentException('Requested dimensions are too small: ' + width + 'x' + height);
}
var errorCorrectionLevel = library_1.QRCodeDecoderErrorCorrectionLevel.L;
var quietZone = BrowserQRCodeSvgWriter.QUIET_ZONE_SIZE;
if (hints) {
if (undefined !== hints.get(library_1.EncodeHintType.ERROR_CORRECTION)) {
var correctionStr = hints.get(library_1.EncodeHintType.ERROR_CORRECTION).toString();
errorCorrectionLevel = library_1.QRCodeDecoderErrorCorrectionLevel.fromString(correctionStr);
}
if (undefined !== hints.get(library_1.EncodeHintType.MARGIN)) {
quietZone = Number.parseInt(hints.get(library_1.EncodeHintType.MARGIN).toString(), 10);
}
}
var code = library_1.QRCodeEncoder.encode(contents, errorCorrectionLevel, hints);
return this.renderResult(code, width, height, quietZone);
};
/**
* Renders the result and then appends it to the DOM.
*/
BrowserQRCodeSvgWriter.prototype.writeToDom = function (containerElement, contents, width, height, hints) {
if (typeof containerElement === 'string') {
var targetEl = document.querySelector(containerElement);
if (!targetEl) {
throw new Error('Could no find the target HTML element.');
}
containerElement = targetEl;
}
var 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).
*/
BrowserQRCodeSvgWriter.prototype.renderResult = function (code, width /*int*/, height /*int*/, quietZone /*int*/) {
var input = code.getMatrix();
if (input === null) {
throw new library_1.IllegalStateException();
}
var inputWidth = input.getWidth();
var inputHeight = input.getHeight();
var qrWidth = inputWidth + (quietZone * 2);
var qrHeight = inputHeight + (quietZone * 2);
var outputWidth = Math.max(width, qrWidth);
var outputHeight = Math.max(height, qrHeight);
var 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.
var leftPadding = Math.floor((outputWidth - (inputWidth * multiple)) / 2);
var topPadding = Math.floor((outputHeight - (inputHeight * multiple)) / 2);
var svgElement = this.createSVGElement(outputWidth, outputHeight);
for (var inputY = 0, outputY = topPadding; inputY < inputHeight; inputY++, outputY += multiple) {
// Write the contents of this row of the barcode
for (var inputX = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) {
if (input.get(inputX, inputY) === 1) {
var 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
*/
BrowserQRCodeSvgWriter.prototype.createSVGElement = function (w, h) {
var svgElement = document.createElementNS(svgNs, 'svg');
var width = w.toString();
var 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
*/
BrowserQRCodeSvgWriter.prototype.createSvgRectElement = function (x, y, w, h) {
var 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;
return BrowserQRCodeSvgWriter;
}());
exports.BrowserQRCodeSvgWriter = BrowserQRCodeSvgWriter;
//# sourceMappingURL=BrowserQRCodeSvgWriter.js.map
@@ -0,0 +1 @@
{"version":3,"file":"BrowserQRCodeSvgWriter.js","sourceRoot":"","sources":["../../../src/writers/BrowserQRCodeSvgWriter.ts"],"names":[],"mappings":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an.
*/
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,CAAC,MAAM,CAAC,CAAC;QADV,WAAM,GAAN,MAAM,CAAmB;QAF5C,sBAAiB,GAAuB,IAAI,CAAC;QAInD,IAAI,CAAC,MAAM,GAAG,gCAAgC,CAAC,6BAA6B,CAAC,MAAM,CAAC,CAAC;IACvF,CAAC;IA9CO,MAAM,CAAC,6BAA6B,CAAC,MAAyB;QACpE,IAAI,SAAS,CAAC;QAEd,IAA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VisualMediaElement = 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,CAAC,MAAM,KAAK,CAAC,EAAE;YACzB,MAAM,IAAI,wBAAwB,CAAC,sBAAsB,CAAC,CAAC;SAC5D;QAED,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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AAC,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,SAAS,KAAK,KAAK,CAAC,GAAG,CAAC,cAAc,CAAC,gBAAgB,CAAC,EAAE;gBAC5D,MAAM,aAAa,GAAG,KAAK,CAAC,GAAG,CAAC,cAAc,CAAC,gBAAgB,CAAC,CAAC,QAAQ,EAAE,CAAC;gBAC5E,oBAAoB,GAAG,iCAAiC,CAAC,UAAU,CAAC,aAAa,CAAC,CAAC;aACpF;YAED,IAAI,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,EAAE,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC;QACzC,IAAI,CAAC,YAAY,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;QAErC,OAAO,IAAI,CAAC;IACd,CAAC;;AA9JuB,sCAAe,GAAG,CAAC,CAAC;AAiK9C,OAAO,EAAE,sBAAsB,EAAE,CAAC"}
@@ -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;
+2
View File
@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=DecodeContinuouslyCallback.js.map

Some files were not shown because too many files have changed in this diff Show More