capacitor-plugin-scanbot-sdk
Version:
Scanbot Document and Barcode Scanner SDK for Capacitor
1,351 lines (1,306 loc) • 1.47 MB
JavaScript
var capacitorScanbotSDKCapacitor = (function (exports, core) {
'use strict';
/// Auto-generated with ScanbotSDKCodegenV3. Modifications will be overwritten.
/// Generated from core/schemas/JSONSerializationTypes.yaml
/**
Configuration used to serialize an object to json.
*/
class ToJsonConfiguration {
/** @param source {@displayType `DeepPartial<ToJsonConfiguration>`} */
constructor(source = {}) {
/**
Serialize images in the object to json. If false, then fields that contain images are not serialized.
Default is true
*/
this.serializeImages = true;
/**
Image serialization mode.
Default is REFERENCE
*/
this.imageSerializationMode = 'REFERENCE';
if (source.serializeImages !== undefined) {
this.serializeImages = source.serializeImages;
}
if (source.imageSerializationMode !== undefined) {
this.imageSerializationMode = source.imageSerializationMode;
}
}
serialize(config = new ToJsonConfiguration()) {
return {
serializeImages: this.serializeImages,
imageSerializationMode: this.imageSerializationMode,
};
}
}
/** @hidden */
const ImageSerializationModeValues = ['REFERENCE', 'BUFFER'];
/// Auto-generated with ScanbotSDKCodegenV3. Modifications will be overwritten.
/// Generated from core/schemas/Geometry.yaml
/**
Represents a line segment in 2D space.
*/
class LineSegmentInt {
/** @param source {@displayType `DeepPartial<LineSegmentInt>`} */
constructor(source = {}) {
if (source.start !== undefined) {
this.start = { x: source.start.x, y: source.start.y };
}
else {
throw new Error('start must be present in constructor argument');
}
if (source.end !== undefined) {
this.end = { x: source.end.x, y: source.end.y };
}
else {
throw new Error('end must be present in constructor argument');
}
}
serialize(config = new ToJsonConfiguration()) {
return {
start: this.start,
end: this.end,
};
}
}
/**
Represents a line segment in 2D space.
*/
class LineSegmentFloat {
/** @param source {@displayType `DeepPartial<LineSegmentFloat>`} */
constructor(source = {}) {
if (source.start !== undefined) {
this.start = { x: source.start.x, y: source.start.y };
}
else {
throw new Error('start must be present in constructor argument');
}
if (source.end !== undefined) {
this.end = { x: source.end.x, y: source.end.y };
}
else {
throw new Error('end must be present in constructor argument');
}
}
serialize(config = new ToJsonConfiguration()) {
return {
start: this.start,
end: this.end,
};
}
}
/**
Aspect ratio is the ratio of the width to the height of an image or screen.
*/
class AspectRatio {
/** @param source {@displayType `DeepPartial<AspectRatio>`} */
constructor(source = {}) {
/**
Width component of the aspect ratio.
Default is 1.0
*/
this.width = 1.0;
/**
Height component of the aspect ratio.
Default is 1.0
*/
this.height = 1.0;
if (source.width !== undefined) {
this.width = source.width;
}
if (source.height !== undefined) {
this.height = source.height;
}
}
serialize(config = new ToJsonConfiguration()) {
return {
width: this.width,
height: this.height,
};
}
}
/**
* @internal
* @hidden
*/
const ScanbotSDKPlugin = core.registerPlugin('ScanbotSDKCapacitor', {});
class SBError extends Error {
constructor(message) {
super(message);
}
}
class InvalidLicenseError extends SBError {
constructor(message) {
super(message);
this.type = 'InvalidLicense';
}
}
class NullPointerError extends SBError {
constructor(message) {
super(message);
this.type = 'NullPointer';
}
}
class InvalidArgumentError extends SBError {
constructor(message) {
super(message);
this.type = 'InvalidArgument';
}
}
class InvalidImageRefError extends SBError {
constructor(message) {
super(message);
this.type = 'InvalidImageRef';
}
}
class ComponentUnavailableError extends SBError {
constructor(message) {
super(message);
this.type = 'ComponentUnavailable';
}
}
class IllegalStateError extends SBError {
constructor(message) {
super(message);
this.type = 'IllegalState';
}
}
class IOError extends SBError {
constructor(message) {
super(message);
this.type = 'IOError';
}
}
class InvalidDataError extends SBError {
constructor(message) {
super(message);
this.type = 'InvalidData';
}
}
class OutOfMemoryError extends SBError {
constructor(message) {
super(message);
this.type = 'OutOfMemory';
}
}
class TimeoutError extends SBError {
constructor(message) {
super(message);
this.type = 'Timeout';
}
}
class UnknownError extends SBError {
constructor(message) {
super(message);
this.type = 'Unknown';
}
}
class ProcessError extends SBError {
constructor(message, code) {
super(message);
this.type = 'ProcessError';
this.code = code;
}
}
/**
* @internal
* @hidden
*/
function createSBError(err) {
const code = Number(err.code);
const message = err.message || err.errorMessage || 'An unknown error occurred';
switch (code) {
case 1:
return new UnknownError(message);
case 2:
return new InvalidLicenseError(message);
case 3:
return new NullPointerError(message);
case 4:
return new InvalidArgumentError(message);
case 5:
return new InvalidImageRefError(message);
case 6:
return new ComponentUnavailableError(message);
case 7:
return new IllegalStateError(message);
case 8:
return new IOError(message);
case 9:
return new InvalidDataError(message);
case 11:
return new OutOfMemoryError(message);
case 12:
return new TimeoutError(message);
default: {
if (code >= 100) {
return new ProcessError(message, code);
}
return new UnknownError(message);
}
}
}
/// Auto-generated with ScanbotSDKCodegenV3. Modifications will be overwritten.
/// Generated from core/schemas/ObjectPoolTypes.yaml
/**
Profile info of a reference-counted stored object.
*/
class RefCountedObjectProfile {
/** @param source {@displayType `DeepPartial<RefCountedObjectProfile>`} */
constructor(source = {}) {
/**
Number of strong references associated with the object. The strong reference count increases when a new instance of a platform ImageRef class is created from the object's unique ID and decreases when the ImageRef instance is destroyed.
Default is 0
*/
this.strongReferences = 0;
/**
Number of serialized references to the object. The serialized reference count increases when an ImageRef is written to JSON or a Parcel on Android and decrease when the respective JSON or Parcel is deserialized.
Default is 0
*/
this.serializedReferences = 0;
if (source.uniqueId !== undefined) {
this.uniqueId = source.uniqueId;
}
else {
throw new Error('uniqueId must be present in constructor argument');
}
if (source.timestampCreated !== undefined) {
this.timestampCreated = source.timestampCreated;
}
else {
throw new Error('timestampCreated must be present in constructor argument');
}
if (source.strongReferences !== undefined) {
this.strongReferences = source.strongReferences;
}
if (source.serializedReferences !== undefined) {
this.serializedReferences = source.serializedReferences;
}
}
serialize(config = new ToJsonConfiguration()) {
return {
uniqueId: this.uniqueId,
timestampCreated: this.timestampCreated,
strongReferences: this.strongReferences,
serializedReferences: this.serializedReferences,
};
}
}
/// Auto-generated with ScanbotSDKCodegenV3. Modifications will be overwritten.
/// Generated from core/schemas/ImageRefTypes.yaml
/** @hidden */
const ColorConversionValues = ['GRAY', 'COLOR', 'ANY_COLOR', 'UNCHANGED'];
/** @hidden */
const CanvasColorValues = ['WHITE', 'BLACK'];
/**
Image Info.
*/
class ImageInfo {
/** @param source {@displayType `DeepPartial<ImageInfo>`} */
constructor(source = {}) {
if (source.height !== undefined) {
this.height = source.height;
}
else {
throw new Error('height must be present in constructor argument');
}
if (source.width !== undefined) {
this.width = source.width;
}
else {
throw new Error('width must be present in constructor argument');
}
if (source.maxByteSize !== undefined) {
this.maxByteSize = source.maxByteSize;
}
else {
throw new Error('maxByteSize must be present in constructor argument');
}
}
serialize(config = new ToJsonConfiguration()) {
return {
height: this.height,
width: this.width,
maxByteSize: this.maxByteSize,
};
}
}
/** @hidden */
const PathLoadModeValues = ['EAGER', 'LAZY', 'LAZY_WITH_COPY'];
/** @hidden */
const BufferLoadModeValues = ['EAGER', 'LAZY'];
/** @hidden */
const EncodingFormatValues = ['JPEG', 'PNG'];
/** @hidden */
const EncryptionModeValues = ['REQUIRED', 'DISABLED', 'AUTO'];
/**
Basic options for loading image.
*/
class BasicImageLoadOptions {
/** @param source {@displayType `DeepPartial<BasicImageLoadOptions>`} */
constructor(source = {}) {
/**
If the rect is not empty, the image will be cropped to this rect before processing.
*/
this.cropRect = { x: 0, y: 0, width: 0, height: 0 };
/**
CanvasColor color to use when converting images with alpha channel to images without alpha channel.
Default is WHITE
*/
this.canvasColor = 'WHITE';
if (source.cropRect !== undefined) {
this.cropRect = {
x: source.cropRect.x,
y: source.cropRect.y,
width: source.cropRect.width,
height: source.cropRect.height,
};
}
if (source.canvasColor !== undefined) {
this.canvasColor = source.canvasColor;
}
}
}
/**
Options for loading images that come from sensor.
*/
class RawImageLoadOptions {
/** @param source {@displayType `DeepPartial<RawImageLoadOptions>`} */
constructor(source = {}) {
/**
If the rect is not empty, the image will be cropped to this rect before processing.
*/
this.cropRect = { x: 0, y: 0, width: 0, height: 0 };
/**
Location of the image origin in the image coordinate system.
During loading images are flipped such that after the flip their new origin is in their top-left corner.
For example, an image coming from the front camera might have its origin set to the top-right, which will flip it along its vertical axis to create a mirror effect.
The origin is interpreted net of the image orientation. The origin rotates together with the image. The origin value is interpreted and the resulting flip executed AFTER the image matrix has been reoriented to have a neutral orientation.
Default is TOP_LEFT
*/
this.origin = 'TOP_LEFT';
/**
CanvasColor color to use when converting images with alpha channel to images without alpha channel.
Default is WHITE
*/
this.canvasColor = 'WHITE';
/**
Rotation that should be applied to the image to recover correct orientation. Is applied before cropping.
Default is NONE
*/
this.orientation = 'NONE';
if (source.cropRect !== undefined) {
this.cropRect = {
x: source.cropRect.x,
y: source.cropRect.y,
width: source.cropRect.width,
height: source.cropRect.height,
};
}
if (source.origin !== undefined) {
this.origin = source.origin;
}
if (source.canvasColor !== undefined) {
this.canvasColor = source.canvasColor;
}
if (source.orientation !== undefined) {
this.orientation = source.orientation;
}
}
}
/**
Options for loading image from path.
*/
class PathImageLoadOptions {
/** @param source {@displayType `DeepPartial<PathImageLoadOptions>`} */
constructor(source = {}) {
/**
If the rect is not empty, the image will be cropped to this rect before processing.
*/
this.cropRect = { x: 0, y: 0, width: 0, height: 0 };
/**
Color conversion to apply during image loading.
Default is ANY_COLOR
*/
this.colorConversion = 'ANY_COLOR';
/**
CanvasColor color to use when converting images with alpha channel to images without alpha channel.
Default is WHITE
*/
this.canvasColor = 'WHITE';
/**
Load mode.
Default is EAGER
*/
this.loadMode = 'EAGER';
/**
Encryption mode.
Default is AUTO
*/
this.encryptionMode = 'AUTO';
if (source.cropRect !== undefined) {
this.cropRect = {
x: source.cropRect.x,
y: source.cropRect.y,
width: source.cropRect.width,
height: source.cropRect.height,
};
}
if (source.colorConversion !== undefined) {
this.colorConversion = source.colorConversion;
}
if (source.canvasColor !== undefined) {
this.canvasColor = source.canvasColor;
}
if (source.loadMode !== undefined) {
this.loadMode = source.loadMode;
}
if (source.encryptionMode !== undefined) {
this.encryptionMode = source.encryptionMode;
}
}
}
/**
Options for loading image from buffer.
*/
class BufferImageLoadOptions {
/** @param source {@displayType `DeepPartial<BufferImageLoadOptions>`} */
constructor(source = {}) {
/**
If the rect is not empty, the image will be cropped to this rect before processing.
*/
this.cropRect = { x: 0, y: 0, width: 0, height: 0 };
/**
Color conversion to apply during image loading.
Default is ANY_COLOR
*/
this.colorConversion = 'ANY_COLOR';
/**
CanvasColor color to use when converting images with alpha channel to images without alpha channel.
Default is WHITE
*/
this.canvasColor = 'WHITE';
/**
Load mode.
Default is EAGER
*/
this.loadMode = 'EAGER';
if (source.cropRect !== undefined) {
this.cropRect = {
x: source.cropRect.x,
y: source.cropRect.y,
width: source.cropRect.width,
height: source.cropRect.height,
};
}
if (source.colorConversion !== undefined) {
this.colorConversion = source.colorConversion;
}
if (source.canvasColor !== undefined) {
this.canvasColor = source.canvasColor;
}
if (source.loadMode !== undefined) {
this.loadMode = source.loadMode;
}
}
}
/**
Options for saving image to a path.
*/
class SaveImageOptions {
/** @param source {@displayType `DeepPartial<SaveImageOptions>`} */
constructor(source = {}) {
/**
Quality parameter is for JPEG only and is in range 0 to 100. If -1, then the value from hibernation is used.
In case the ImageRef was created in lazy load-mode and originally has the same format as the requested to save,
then setting quality to -1 leads to simply copying from source to destination,
which is time efficient and prevents quality loss caused by decoding the JPEG and then re-encoding it.
Default is -1
*/
this.quality = -1;
/**
If `true`, the encoder will spend extra time when saving JPEG files
to improve the compression rate. Enabling this option has no impact on quality.
Default is false
*/
this.optimize = false;
/**
Encryption mode.
Default is AUTO
*/
this.encryptionMode = 'AUTO';
if (source.quality !== undefined) {
this.quality = source.quality;
}
if (source.optimize !== undefined) {
this.optimize = source.optimize;
}
if (source.encryptionMode !== undefined) {
this.encryptionMode = source.encryptionMode;
}
}
}
/**
Options for encoding image.
*/
class EncodeImageOptions {
/** @param source {@displayType `DeepPartial<EncodeImageOptions>`} */
constructor(source = {}) {
/**
Quality parameter is for JPEG only and is in range 0 to 100. If -1, then the value from hibernation is used.
In case the ImageRef was created in lazy load-mode and originally has the same format as the requested to save,
then setting quality to -1 leads to simply copying from source to destination,
which is time efficient and prevents quality loss caused by decoding the JPEG and then re-encoding it.
Default is -1
*/
this.quality = -1;
/**
If `true`, the encoder will spend extra time when saving JPEG files
to improve the compression rate. Enabling this option has no impact on quality.
Default is false
*/
this.optimize = false;
/**
Image format.
Default is JPEG
*/
this.format = 'JPEG';
if (source.quality !== undefined) {
this.quality = source.quality;
}
if (source.optimize !== undefined) {
this.optimize = source.optimize;
}
if (source.format !== undefined) {
this.format = source.format;
}
}
}
/** @hidden */
const ImageSourceTypeValues = [
'API',
'PLATFORM_IMAGE',
'CAMERA',
'FILE',
'BUFFER',
'OTHER',
];
/**
Description of source from which the ImageRef was created.
*/
class ImageSource {
/** @param source {@displayType `DeepPartial<ImageSource>`} */
constructor(source = {}) {
if (source.type !== undefined) {
this.type = source.type;
}
else {
throw new Error('type must be present in constructor argument');
}
if (source.filePath !== undefined) {
this.filePath = source.filePath != null ? source.filePath : null;
}
else {
throw new Error('filePath must be present in constructor argument');
}
}
serialize(config = new ToJsonConfiguration()) {
return {
type: this.type,
filePath: this.filePath != null ? this.filePath : null,
};
}
}
/**
ImageRef profile part specific to image information.
*/
class ImageProfile {
/** @param source {@displayType `DeepPartial<ImageProfile>`} */
constructor(source = {}) {
/**
Memory consumption of a memory-backed bitmap. Zero, if the image is hibernating.
Default is 0
*/
this.bitmapMemoryConsumption = 0;
/**
Memory consumption of the hibernation buffer. Zero, if the image is not hibernating, or is hibernated to a file.
Default is 0
*/
this.hibernationMemoryConsumption = 0;
if (source.bitmapMemoryConsumption !== undefined) {
this.bitmapMemoryConsumption = source.bitmapMemoryConsumption;
}
if (source.hibernationMemoryConsumption !== undefined) {
this.hibernationMemoryConsumption = source.hibernationMemoryConsumption;
}
}
serialize(config = new ToJsonConfiguration()) {
return {
bitmapMemoryConsumption: this.bitmapMemoryConsumption,
hibernationMemoryConsumption: this.hibernationMemoryConsumption,
};
}
}
/**
ImageRef profile which provides detailed information about stored object.
*/
class ImageRefProfile {
/** @param source {@displayType `DeepPartial<ImageRefProfile>`} */
constructor(source = {}) {
if (source.refInfo !== undefined) {
this.refInfo = new RefCountedObjectProfile(source.refInfo);
}
else {
throw new Error('refInfo must be present in constructor argument');
}
if (source.imageInfo !== undefined) {
this.imageInfo = new ImageProfile(source.imageInfo);
}
else {
throw new Error('imageInfo must be present in constructor argument');
}
if (source.imageSource !== undefined) {
this.imageSource = source.imageSource != null ? new ImageSource(source.imageSource) : null;
}
else {
throw new Error('imageSource must be present in constructor argument');
}
}
serialize(config = new ToJsonConfiguration()) {
return {
refInfo: this.refInfo.serialize(config),
imageInfo: this.imageInfo.serialize(config),
imageSource: this.imageSource != null ? this.imageSource.serialize(config) : null,
};
}
}
/**
Snapshot of all alive ImageRefs.
*/
class ImageRefPoolSnapshot {
/** @param source {@displayType `DeepPartial<ImageRefPoolSnapshot>`} */
constructor(source = {}) {
/**
Estimation of total memory consumption of ImageRefs.
Default is 0
*/
this.totalMemoryConsumption = 0;
if (source.imageRefProfiles !== undefined) {
this.imageRefProfiles = source.imageRefProfiles.map((it) => {
return new ImageRefProfile(it);
});
}
else {
throw new Error('imageRefProfiles must be present in constructor argument');
}
if (source.totalMemoryConsumption !== undefined) {
this.totalMemoryConsumption = source.totalMemoryConsumption;
}
}
serialize(config = new ToJsonConfiguration()) {
return {
imageRefProfiles: this.imageRefProfiles.map((it) => {
return it.serialize(config);
}),
totalMemoryConsumption: this.totalMemoryConsumption,
};
}
}
/**
difference between two snapshots.
*/
class ImageRefPoolSnapshotsDiff {
/** @param source {@displayType `DeepPartial<ImageRefPoolSnapshotsDiff>`} */
constructor(source = {}) {
/**
Difference between total memory consumption in two snapshots.
Default is 0
*/
this.totalMemoryConsumptionDiff = 0;
if (source.totalMemoryConsumptionDiff !== undefined) {
this.totalMemoryConsumptionDiff = source.totalMemoryConsumptionDiff;
}
if (source.removed !== undefined) {
this.removed = source.removed.map((it) => {
return it;
});
}
else {
throw new Error('removed must be present in constructor argument');
}
if (source.added !== undefined) {
this.added = source.added.map((it) => {
return it;
});
}
else {
throw new Error('added must be present in constructor argument');
}
if (source.modified !== undefined) {
this.modified = source.modified.map((it) => {
return it;
});
}
else {
throw new Error('modified must be present in constructor argument');
}
}
serialize(config = new ToJsonConfiguration()) {
return {
totalMemoryConsumptionDiff: this.totalMemoryConsumptionDiff,
removed: this.removed.map((it) => {
return it;
}),
added: this.added.map((it) => {
return it;
}),
modified: this.modified.map((it) => {
return it;
}),
};
}
}
class AutoReleasePool {
constructor() {
this.poolObjects = [];
}
releaseAll() {
for (const obj of this.poolObjects) {
if (!obj.isRetained()) {
obj.release();
}
}
}
addObject(obj) {
this.poolObjects.push(obj);
}
}
AutoReleasePool.globalPull = null;
AutoReleasePool.globalPullReferences = 0;
async function autorelease(computation) {
if (AutoReleasePool.globalPull === null) {
AutoReleasePool.globalPull = new AutoReleasePool();
}
AutoReleasePool.globalPullReferences++;
const releasePoolRef = () => {
AutoReleasePool.globalPullReferences--;
if (AutoReleasePool.globalPullReferences === 0) {
AutoReleasePool.globalPull.releaseAll();
AutoReleasePool.globalPull = null;
}
};
try {
return await computation();
}
finally {
releasePoolRef();
}
}
class AutoReleasable {
constructor(uniqueId) {
this.retained = false;
if (uniqueId) {
if (AutoReleasePool.globalPull === null) {
const errorMessage = 'Initializing an object that contains a ScanbotImage instance as REFERENCE must be wrapped inside an autorelease pool. For example:' +
'\n autorelease(()=>{' +
'\n const barcodeItem = new BarcodeItem(source);' +
'\n });';
throw new InvalidImageRefError(errorMessage);
}
AutoReleasePool.globalPull.addObject(this);
}
}
isRetained() {
return this.retained;
}
retain() {
this.retained = true;
}
}
class ImageRef extends AutoReleasable {
get buffer() {
return this._buffer;
}
constructor(uniqueId, buffer) {
super(uniqueId);
this.released = false;
this.uniqueId = uniqueId;
this._buffer = buffer;
}
static from(source) {
if (source.buffer) {
return new ImageRef(undefined, source.buffer);
}
else {
return ImageRef.deserialize(source);
}
}
static deserialize(serializedRef) {
if (!serializedRef.uniqueId) {
throw new InvalidImageRefError('uniqueId must be present in serializedRef argument');
}
// The promise is intentionally not awaited here
ScanbotSDKPlugin.imageRefDeserialize({ uniqueId: serializedRef.uniqueId })
.then((wrappedResult) => {
if (!wrappedResult.result) {
console.error(`Unsuccessful deserialization of ImageRef with uniqueId ${serializedRef.uniqueId}`);
}
})
.catch((error) => {
console.error(`Error while deserializing ImageRef with uniqueId ${serializedRef.uniqueId}: ${error}`);
});
return new ImageRef(serializedRef.uniqueId, undefined);
}
/**
* Converts the Image Ref to Json representation
*/
async serialize(imageSerializationMode) {
if (imageSerializationMode === 'BUFFER') {
const encodedImage = await this.encodeImage();
if (encodedImage) {
return { buffer: encodedImage };
}
else {
return null;
}
}
else {
this.throwErrorIfReleased();
this.throwErrorIfUniqueIdIsMissing();
// The promise is intentionally not awaited here
ScanbotSDKPlugin.imageRefSerialize({ uniqueId: this.uniqueId })
.then((wrappedResult) => {
if (!wrappedResult.result) {
console.error(`Unsuccessful serialization of ImageRef with uniqueId ${this.uniqueId}`);
}
})
.catch((error) => {
console.error(`Error while serializing ImageRef with uniqueId ${this.uniqueId}: ${error}`);
});
return { uniqueId: this.uniqueId };
}
}
/**
* Creates ImageRef with uniqueId from the file uri to an image.
*/
static async fromImageFileUri(uri, options = new PathImageLoadOptions()) {
try {
const serializedImageRefUniqueId = (await ScanbotSDKPlugin.imageRefFromImageFileUri({
uri,
options,
})).result;
return ImageRef.deserialize({ uniqueId: serializedImageRefUniqueId });
}
catch (error) {
console.error(error);
return null;
}
}
/**
* Creates ImageRef with uniqueId from base64 encoded buffer, e.g. from jpeg.
*/
static async fromEncodedBuffer(buffer, options = new BufferImageLoadOptions()) {
try {
const serializedImageRefUniqueId = (await ScanbotSDKPlugin.imageRefFromEncodedBuffer({
buffer,
options,
})).result;
return ImageRef.deserialize({ uniqueId: serializedImageRefUniqueId });
}
catch (error) {
console.error(error);
return null;
}
}
/**
* Compresses ImageRef and stores it either on disk or in memory according to global settings.
* If uniqueId is not set or the image is already released, an exception will be thrown.
*/
async hibernate() {
this.throwErrorIfUniqueIdIsMissing();
this.throwErrorIfReleased();
try {
await ScanbotSDKPlugin.imageRefHibernate({ uniqueId: this.uniqueId });
}
catch (error) {
console.error(error);
}
}
/**
* Releases native resources stored by the ref.
* If two different ImageRef objects have the same uniqueId both of them become cleared.
* If uniqueId is not set or the image is already released, an exception will be thrown.
*/
async clear() {
this.throwErrorIfUniqueIdIsMissing();
this.throwErrorIfReleased();
try {
await ScanbotSDKPlugin.imageRefClear({ uniqueId: this.uniqueId });
}
catch (error) {
console.error(error);
}
}
/**
* Information about stored image as reference.
* If uniqueId is not set or the image is already released, an exception will be thrown.
*/
async info() {
this.throwErrorIfUniqueIdIsMissing();
this.throwErrorIfReleased();
try {
const imageInfo = await ScanbotSDKPlugin.imageRefInfo({ uniqueId: this.uniqueId });
return new ImageInfo(imageInfo);
}
catch (error) {
console.error(error);
return null;
}
}
/**
* Saves the stored image with the given options.
* If uniqueId is not set or the image is already released, an exception will be thrown.
*/
async saveImage(path, options = new SaveImageOptions()) {
this.throwErrorIfUniqueIdIsMissing();
this.throwErrorIfReleased();
try {
return (await ScanbotSDKPlugin.imageRefSaveImage({ uniqueId: this.uniqueId, path, options })).result;
}
catch (error) {
console.error(error);
return false;
}
}
/**
* Encode image.
*/
async encodeInPlace() {
if (this._buffer) ;
else {
this.throwErrorIfReleased();
this.throwErrorIfUniqueIdIsMissing();
try {
const imageAsBuffer = (await ScanbotSDKPlugin.imageRefEncodeImage({
uniqueId: this.uniqueId,
options: new EncodeImageOptions(),
})).result;
if (imageAsBuffer) {
this._buffer = imageAsBuffer;
}
}
catch (error) {
console.error(error);
}
}
}
/**
* Returns the stored image as base64.
*/
async encodeImage(options) {
if (this._buffer) {
if (options) {
throw new InvalidImageRefError('EncodeImageOptions are not available when image is already encoded to base64');
}
return this._buffer;
}
else {
this.throwErrorIfReleased();
this.throwErrorIfUniqueIdIsMissing();
try {
return (await ScanbotSDKPlugin.imageRefEncodeImage({
uniqueId: this.uniqueId,
options: options !== null && options !== void 0 ? options : new EncodeImageOptions(),
})).result;
}
catch (error) {
console.error(error);
return null;
}
}
}
/**
* Releases strong reference to the image.
* If uniqueId to the image is not set, an exception will be thrown.
*/
release() {
this.throwErrorIfUniqueIdIsMissing();
if (!this.released) {
// The promise is intentionally not awaited here
ScanbotSDKPlugin.imageRefRelease({ uniqueId: this.uniqueId }).catch((error) => {
console.error(`Error while releasing ImageRef with uniqueId ${this.uniqueId}: ${error}`);
});
this.released = true;
}
}
/**
* Returns a snapshot of all alive ImageRefs.
* The snapshot contains a list of ImageRefs with information such as in-memory size.
*/
static async makeSnapshot() {
try {
const snapshot = await ScanbotSDKPlugin.makeSnapshot();
return new ImageRefPoolSnapshot(snapshot);
}
catch (error) {
console.error(error);
return null;
}
}
/**
* Releases all alive images despite any existing references.
*/
static releaseAll() {
// The promise is intentionally not awaited here
ScanbotSDKPlugin.imageRefReleaseAll().catch(() => { });
}
throwErrorIfUniqueIdIsMissing() {
if (!this.uniqueId) {
throw new InvalidImageRefError('uniqueId is missing');
}
}
throwErrorIfReleased() {
if (this.released) {
throw new InvalidImageRefError(`ImageRef with uniqueId ${this.uniqueId} has been released`);
}
}
}
/// Auto-generated with ScanbotSDKCodegenV3. Modifications will be overwritten.
/// Generated from core/schemas/DocumentEnhancerTypes.yaml
/** @hidden */
const DocumentStraighteningModeValues = ['NONE', 'STRAIGHTEN'];
/**
Configuration for document straightening.
*/
class DocumentStraighteningParameters {
/** @param source {@displayType `DeepPartial<DocumentStraighteningParameters>`} */
constructor(source = {}) {
/**
Type of document straightening to apply.
Default is STRAIGHTEN
*/
this.straighteningMode = 'STRAIGHTEN';
/**
By default, aspect ratio of the straightened document is automatically determined based on the detected document corners.
If the document is significantly deformed, the estimated aspect ratio may be inaccurate.
In such cases, providing a list of expected aspect ratios may help improve the accuracy of the straightening.
The closest matching aspect ratio from the list will be used.
Note, that if for a given paper format you want to support both portrait and landscape orientations, you need to provide both aspect ratios (e.g. 1:√2 and √2:1 for A series papers).
*/
this.aspectRatios = [];
if (source.straighteningMode !== undefined) {
this.straighteningMode = source.straighteningMode;
}
if (source.aspectRatios !== undefined) {
this.aspectRatios = source.aspectRatios.map((it) => {
return new AspectRatio(it);
});
}
}
serialize(config = new ToJsonConfiguration()) {
return {
straighteningMode: this.straighteningMode,
aspectRatios: this.aspectRatios.map((it) => {
return it.serialize(config);
}),
};
}
}
/**
Result of the document straightening.
*/
class DocumentStraighteningResult {
/** @param source {@displayType `DeepPartial<DocumentStraighteningResult>`} */
constructor(source = {}) {
/**
The straightened document image. Can be null if no document was detected.
*/
this.straightenedImage = null;
this._released = false;
if (source.straightenedImage !== undefined) {
this.straightenedImage = source.straightenedImage != null ? ImageRef.from(source.straightenedImage) : null;
}
}
async serialize(config = new ToJsonConfiguration()) {
return {
straightenedImage: config.serializeImages
? this.straightenedImage != null
? await this.straightenedImage.serialize(config.imageSerializationMode)
: null
: undefined,
};
}
release() {
if (this._released) {
return;
}
{
if (this.straightenedImage != null) {
this.straightenedImage.release();
}
}
this._released = true;
}
async encodeImages() {
if (this.straightenedImage != null) {
await this.straightenedImage.encodeInPlace();
}
}
}
/// Auto-generated with ScanbotSDKCodegenV3. Modifications will be overwritten.
/// Generated from core/schemas/ParametricFilters.yaml
/** @hidden */
const OutputModeValues = ['BINARY', 'ANTIALIASED'];
/** @hidden */
const BinarizationFilterPresetValues = [
'PRESET_1',
'PRESET_2',
'PRESET_3',
'PRESET_4',
'PRESET_5',
];
/** @internal */
exports.ParametricFilter = void 0;
(function (ParametricFilter) {
/** @internal */
function from(source) {
const _type = source['_type'];
switch (_type) {
case 'LegacyFilter':
return new LegacyFilter(source);
case 'ScanbotBinarizationFilter':
return new ScanbotBinarizationFilter(source);
case 'CustomBinarizationFilter':
return new CustomBinarizationFilter(source);
case 'ColorDocumentFilter':
return new ColorDocumentFilter(source);
case 'ColorDocumentShadowRemovalFilter':
return new ColorDocumentShadowRemovalFilter(source);
case 'BrightnessFilter':
return new BrightnessFilter(source);
case 'ContrastFilter':
return new ContrastFilter(source);
case 'GrayscaleFilter':
return new GrayscaleFilter(source);
case 'WhiteBlackPointFilter':
return new WhiteBlackPointFilter(source);
default:
throw new Error(`Unknown child class name: ${_type}`);
}
}
ParametricFilter.from = from;
})(exports.ParametricFilter || (exports.ParametricFilter = {}));
/**
Deprecated. Returns the input image unchanged.
*/
class LegacyFilter {
/** @param source {@displayType `DeepPartial<LegacyFilter>`} */
constructor(source = {}) {
this._type = 'LegacyFilter';
/**
Ignored.
Default is 0
*/
this.filterType = 0;
if (source.filterType !== undefined) {
this.filterType = source.filterType;
}
}
serialize(config = new ToJsonConfiguration()) {
return {
_type: this._type,
filterType: this.filterType,
};
}
}
/**
Automatic binarization filter. This filter is a good starting point for most use cases.
*/
class ScanbotBinarizationFilter {
/** @param source {@displayType `DeepPartial<ScanbotBinarizationFilter>`} */
constructor(source = {}) {
this._type = 'ScanbotBinarizationFilter';
/**
Output mode of the filter. BINARY will return a black and white image, GRAYSCALE will return an antialiased grayscale image.
Default is BINARY
*/
this.outputMode = 'BINARY';
if (source.outputMode !== undefined) {
this.outputMode = source.outputMode;
}
}
serialize(config = new ToJsonConfiguration()) {
return {
_type: this._type,
outputMode: this.outputMode,
};
}
}
/**
Automatic binarization filter. This filter is a good starting point for most use cases.
*/
class CustomBinarizationFilter {
/** @param source {@displayType `DeepPartial<CustomBinarizationFilter>`} */
constructor(source = {}) {
this._type = 'CustomBinarizationFilter';
/**
Output mode of the filter. BINARY will return a black and white image, GRAYSCALE will return an antialiased grayscale image.
Default is BINARY
*/
this.outputMode = 'BINARY';
/**
Value controlling the amount of noise removal. Value between 0 and 1.
Too little noise removal may result in a very noisy image, worsening readability.
Too much noise removal may result in the degradation of text, again, worsening readability.
Default is 0.5
*/
this.denoise = 0.5;
/**
Filter radius. The bigger the radius, the slower the filter and generally the less noise in the result.
The radius is used for both shadows removal and the calculation of local statistics in the main body of the filter.
Higher radius usually allows to cope better with regions of light text on dark background.
All the values larger than 127 are clamped to 127.
Default is 32
*/
this.radius = 32;
/**
Preset of binarization filter parameters that are found to perform well on different types of documents.
Default is PRESET_4
*/
this.preset = 'PRESET_4';
if (source.outputMode !== undefined) {
this.outputMode = source.outputMode;
}
if (source.denoise !== undefined) {
this.denoise = source.denoise;
}
if (source.radius !== undefined) {
this.radius = source.radius;
}
if (source.preset !== undefined) {
this.preset = source.preset;
}
}
serialize(config = new ToJsonConfiguration()) {
return {
_type: this._type,
outputMode: this.outputMode,
denoise: this.denoise,
radius: this.radius,
preset: this.preset,
};
}
}
/**
Color document filter. This filter is a good starting point for most use cases.
*/
class ColorDocumentFilter {
/** @param source {@displayType `DeepPartial<ColorDocumentFilter>`} */
constructor(source = {}) {
this._type = 'ColorDocumentFilter';
/**
Strength of contrast enhancement. Typical values are between 0 and 1, although higher values are possible.
Default is 0.5
*/
this.contrastEnhancement = 0.5;
/**
Strength of color saturation enhancement. Typical values are betw