Skip to content

Commit

Permalink
Retrocompatibility with AOT Angular version 8
Browse files Browse the repository at this point in the history
  • Loading branch information
David Faure committed Jul 22, 2024
1 parent 6cd2bcb commit 69838f5
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 43 deletions.
54 changes: 27 additions & 27 deletions projects/ngx-image-compress/src/lib/image-compress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {DOC_ORIENTATION} from './models/DOC_ORIENTATION';
import {UploadResponse} from './models/upload-response';

export class ImageCompress {
static getOrientation = (file: File): Promise<DOC_ORIENTATION> =>
getOrientation = (file: File): Promise<DOC_ORIENTATION> =>
new Promise<DOC_ORIENTATION>((resolve, reject) => {
try {
const reader = new FileReader();
Expand Down Expand Up @@ -48,23 +48,23 @@ export class ImageCompress {
}
});

static uploadFile = (render: Renderer2, multiple = true, rejectOnCancel = false): Promise<UploadResponse | UploadResponse[]> =>
uploadFile = (render: Renderer2, multiple = true, rejectOnCancel = false): Promise<UploadResponse | UploadResponse[]> =>
new Promise(function (resolve, reject) {
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
const isIOS = /iPad|iPhone|iPod/i.test(navigator.userAgent);

Promise.resolve(isSafari || isIOS)
.then(onlyNative => {
if (onlyNative) {
return ImageCompress.generateUploadInputNative(window.document, multiple, rejectOnCancel);
return this.generateUploadInputNative(window.document, multiple, rejectOnCancel);
} else {
return ImageCompress.generateUploadInputRenderer(render, multiple, rejectOnCancel);
return this.generateUploadInputRenderer(render, multiple, rejectOnCancel);
}
})
.then((filesList: FileList | null) => {
const files = filesList ? Array.from(filesList) : [];
const orientationPromises = files.map(file => ImageCompress.getOrientation(file));
const readerPromises = files.map(file => ImageCompress.fileToDataURL(file));
const orientationPromises = files.map(file => this.getOrientation(file));
const readerPromises = files.map(file => this.fileToDataURL(file));

let orientationsResult: DOC_ORIENTATION[] = [];

Expand All @@ -90,7 +90,7 @@ export class ImageCompress {
.catch(err => reject(err));
});

static fileToDataURL = (file: File): Promise<{dataUrl: string; fileName: string}> => {
fileToDataURL = (file: File): Promise<{dataUrl: string; fileName: string}> => {
return new Promise<{dataUrl: string; fileName: string}>((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e: any) => {
Expand All @@ -105,7 +105,7 @@ export class ImageCompress {
});
};

static generateUploadInputRenderer = (render: Renderer2, multiple = true, rejectOnCancel = false) => {
generateUploadInputRenderer = (render: Renderer2, multiple = true, rejectOnCancel = false) => {
let lock = false;
return new Promise<FileList | null>((resolve, reject) => {
const inputElement = render.createElement('input');
Expand Down Expand Up @@ -145,7 +145,7 @@ export class ImageCompress {
});
};

static generateUploadInputNative = (documentNativeApi: any, multiple = true, rejectOnCancel = false) => {
generateUploadInputNative = (documentNativeApi: any, multiple = true, rejectOnCancel = false) => {
let lock = false;
return new Promise<FileList | null>((resolve, reject) => {
const inputElement = documentNativeApi.createElement('input');
Expand Down Expand Up @@ -190,7 +190,7 @@ export class ImageCompress {
});
};

static compress = (
compress = (
imageDataUrlSource: DataUrl,
orientation: DOC_ORIENTATION,
render: Renderer2,
Expand Down Expand Up @@ -268,24 +268,24 @@ export class ImageCompress {
sourceImage.src = imageDataUrlSource;
});

static byteCount = (imgString: DataUrl): number => encodeURI(imgString).split(/%..|./).length - 1;
byteCount = (imgString: DataUrl): number => encodeURI(imgString).split(/%..|./).length - 1;

static uploadGetImageMaxSize = async (
uploadGetImageMaxSize = async (
maxSizeMb: number,
debugMode: boolean,
render: Renderer2,
rejectOnCancel = false
): Promise<UploadResponse> => {
if (debugMode) {
console.debug('NgxImageCompress - Opening upload window');
console.debug('Ngxthis - Opening upload window');
}

const myFile: UploadResponse = (await ImageCompress.uploadFile(render, false, rejectOnCancel)) as UploadResponse;
const myFile: UploadResponse = (await this.uploadFile(render, false, rejectOnCancel)) as UploadResponse;

return await ImageCompress.getImageMaxSize(myFile, maxSizeMb, debugMode, render);
return await this.getImageMaxSize(myFile, maxSizeMb, debugMode, render);
};

static getImageMaxSize = async (
getImageMaxSize = async (
myFile: UploadResponse,
maxSizeMb: number,
debugMode: boolean,
Expand All @@ -296,21 +296,21 @@ export class ImageCompress {
const bytesToMB = (bytes: number) => (bytes / 1024 / 1024).toFixed(2);

if (debugMode) {
console.debug('NgxImageCompress - Opening upload window');
console.debug('Ngxthis - Opening upload window');
}

let compressedFile;

for (let i = 0; i < MAX_TRIES; i++) {
const previousSize = ImageCompress.byteCount(myFile.image);
compressedFile = await ImageCompress.compress(myFile.image, myFile.orientation, render, 50, 100);
const newSize = ImageCompress.byteCount(compressedFile);
console.debug('NgxImageCompress -', 'Compression from', bytesToMB(previousSize), 'MB to', bytesToMB(newSize), 'MB');
const previousSize = this.byteCount(myFile.image);
compressedFile = await this.compress(myFile.image, myFile.orientation, render, 50, 100);
const newSize = this.byteCount(compressedFile);
console.debug('Ngxthis -', 'Compression from', bytesToMB(previousSize), 'MB to', bytesToMB(newSize), 'MB');
if (newSize >= previousSize) {
if (i === 0) {
if (debugMode) {
console.debug(
'NgxImageCompress -',
'Ngxthis -',
"File can't be reduced at all - returning the original",
bytesToMB(previousSize),
'MB large'
Expand All @@ -320,7 +320,7 @@ export class ImageCompress {
} else {
if (debugMode) {
console.debug(
'NgxImageCompress -',
'Ngxthis -',
"File can't be reduced more - returning the best we can, which is ",
bytesToMB(previousSize),
'MB large'
Expand All @@ -331,13 +331,13 @@ export class ImageCompress {
} else {
if (newSize < maxSizeMb * 1024 * 1024) {
if (debugMode) {
console.debug('NgxImageCompress -', 'Here your file', bytesToMB(newSize), 'MB large');
console.debug('Ngxthis -', 'Here your file', bytesToMB(newSize), 'MB large');
}
return {...myFile, image: compressedFile};
} else if (i === 9) {
if (debugMode) {
console.debug(
'NgxImageCompress -',
'Ngxthis -',
"File can't reach the desired size after",
MAX_TRIES,
'tries. Returning file ',
Expand All @@ -349,12 +349,12 @@ export class ImageCompress {
}
}
if (debugMode) {
console.debug('NgxImageCompress -', 'Reached', bytesToMB(newSize), 'MB large. Trying another time after', i + 1, 'times');
console.debug('Ngxthis -', 'Reached', bytesToMB(newSize), 'MB large. Trying another time after', i + 1, 'times');
}
myFile.image = compressedFile;
}
if (debugMode) {
console.debug('NgxImageCompress - Unexpected error');
console.debug('Ngxthis - Unexpected error');
}
throw {};
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ export class NgxImageCaptureComponent {
@Output() imageCaptured = new EventEmitter<DataUrl>();
@Output() errorCapture = new EventEmitter<string>();

@ViewChild('video')
@ViewChild('video', {static: false})
videoElement: ElementRef<HTMLVideoElement> | null = null;
videoStream: MediaStream | null = ViewChild('video');
videoStream: MediaStream | null = ViewChild('video', {static: false});
streamOpened = false;

startVideoCapture() {
Expand All @@ -40,10 +40,10 @@ export class NgxImageCaptureComponent {
.then(stream => {
this.videoStream = stream;
setTimeout(() => {
if (this.videoElement?.nativeElement) {
if (this.videoElement && this.videoElement.nativeElement) {
this.videoElement.nativeElement.srcObject = stream;
}
},100);
}, 100);
})
.catch(error => {
this.errorCapture.emit(`Ngx Image Compress: Could not access the camera. ${error}`);
Expand All @@ -53,15 +53,15 @@ export class NgxImageCaptureComponent {

acquireImage(): void {
const canvas = document.createElement('canvas');
const video = this.videoElement?.nativeElement;
const video = this.videoElement && this.videoElement.nativeElement;
if (!video) {
this.errorCapture.emit('Ngx Image Compress - Error in acquisition of video element.');
this.streamOpened = false;
return;
}
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d')?.drawImage(video, 0, 0);
canvas.getContext('2d') && canvas.getContext('2d').drawImage(video, 0, 0);
const newImage = canvas.toDataURL('jpg', 95);
if (this.videoStream) {
this.videoStream.getVideoTracks().forEach(track => track.stop());
Expand Down
23 changes: 13 additions & 10 deletions projects/ngx-image-compress/src/lib/ngx-image-compress.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,57 +10,60 @@ import {UploadResponse} from './models/upload-response';
export class NgxImageCompressService {
private readonly render: Renderer2;

private imageCompress: ImageCompress;

public DOC_ORIENTATION = DOC_ORIENTATION;

constructor(rendererFactory: RendererFactory2) {
this.render = rendererFactory.createRenderer(null, null);
this.imageCompress = new ImageCompress();
}

/**
* helper to evaluate the compression rate
* @param imgString the image in base64 string format
*/
public byteCount(image: DataUrl) {
return ImageCompress.byteCount(image);
return this.imageCompress.byteCount(image);
}

/**
* Get the correct Orientation value from image tags
*/
public getOrientation(file: File): Promise<DOC_ORIENTATION> {
return ImageCompress.getOrientation(file);
return this.imageCompress.getOrientation(file);
}

/**
* return a promise with the new image data and image orientation
* Nothing happen if no file have been selected
*/
public uploadFile(): Promise<UploadResponse> {
return ImageCompress.uploadFile(this.render, false) as Promise<UploadResponse>;
return this.imageCompress.uploadFile(this.render, false) as Promise<UploadResponse>;
}

/**
* return a promise with an array of image data and image orientation
* Nothing happen if no files have been selected
*/
public uploadMultipleFiles(): Promise<UploadResponse[]> {
return ImageCompress.uploadFile(this.render, true) as Promise<UploadResponse[]>;
return this.imageCompress.uploadFile(this.render, true) as Promise<UploadResponse[]>;
}

/**
* return a promise with the new image data and image orientation
* the promise will reject if no file have been selected
*/
public uploadFileOrReject(): Promise<UploadResponse> {
return ImageCompress.uploadFile(this.render, false, true) as Promise<UploadResponse>;
return this.imageCompress.uploadFile(this.render, false, true) as Promise<UploadResponse>;
}

/**
* return a promise with an array of image data and image orientation
* the promise will reject if no files have been selected
*/
public uploadMultipleFilesOrReject(): Promise<UploadResponse[]> {
return ImageCompress.uploadFile(this.render, true, true) as Promise<UploadResponse[]>;
return this.imageCompress.uploadFile(this.render, true, true) as Promise<UploadResponse[]>;
}

/**
Expand All @@ -84,7 +87,7 @@ export class NgxImageCompressService {
maxWidth = 0,
maxHeight = 0
): Promise<DataUrl> {
return ImageCompress.compress(image, orientation, this.render, ratio, quality, maxWidth, maxHeight);
return this.imageCompress.compress(image, orientation, this.render, ratio, quality, maxWidth, maxHeight);
}

/**
Expand All @@ -94,7 +97,7 @@ export class NgxImageCompressService {
* Put debugMode to true if you have some trouble to print some help using console.debug
*/
public uploadAndGetImageWithMaxSize(maxSizeMb = 1, debugMode = false, rejectOnCancel = false): Promise<DataUrl> {
return ImageCompress.uploadGetImageMaxSize(maxSizeMb, debugMode, this.render, rejectOnCancel)
return this.imageCompress.uploadGetImageMaxSize(maxSizeMb, debugMode, this.render, rejectOnCancel)
.then(uploadResponse => uploadResponse.image)
.catch(e => {
throw e.image;
Expand All @@ -105,13 +108,13 @@ export class NgxImageCompressService {
* Same as before, but return more informations (file name...)
*/
public uploadAndGetImageWithMaxSizeAndMetas(maxSizeMb = 1, debugMode = false, rejectOnCancel = false): Promise<UploadResponse> {
return ImageCompress.uploadGetImageMaxSize(maxSizeMb, debugMode, this.render, rejectOnCancel);
return this.imageCompress.uploadGetImageMaxSize(maxSizeMb, debugMode, this.render, rejectOnCancel);
}

/**
* Not handling the upload, you need to provide the file and the orientation by yourself
*/
public getImageWithMaxSizeAndMetas(file: UploadResponse, maxSizeMb = 1, debugMode = false): Promise<UploadResponse> {
return ImageCompress.getImageMaxSize(file, maxSizeMb, debugMode, this.render);
return this.imageCompress.getImageMaxSize(file, maxSizeMb, debugMode, this.render);
}
}

0 comments on commit 69838f5

Please sign in to comment.