All files / lib image-compress.ts

82.53% Statements 156/189
69.56% Branches 48/69
80.55% Functions 29/36
82.32% Lines 149/181

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355              9x 9x 9x 9x 9x 9x 1x   8x 1x   7x 7x 7x 14x 14x 14x 7x     7x 7x 7x 7x 7x 21x 7x     7x     7x         9x               5x 5x 5x   5x   5x     5x       5x 5x 5x   5x   5x   5x 5x     5x           5x 1x   4x                 7x 7x 7x   6x   7x 7x   1x           8x 8x 8x 8x 8x 8x   8x 2x     8x 8x     8x 8x 8x 8x     8x                           8x         1x 1x 1x 1x 1x 1x 1x   1x 1x     1x   1x                   1x                               1x                         14x 14x 14x 14x     14x 14x 14x   14x       14x 14x   14x 13x 4x 4x 4x       14x 14x 14x 14x 14x   14x   14x 7x 7x 2x 2x 2x 2x 2x 5x 2x 2x 2x 2x 2x 3x 2x 2x 2x 2x 2x     1x     14x   14x   14x     14x 14x       23x     3x 2x     3x   3x       3x   8x   3x 2x         3x 3x 3x 3x 3x 3x 1x 1x 1x             1x                         2x 2x 1x   2x                                                    
import {Renderer2} from '@angular/core';
import {DataUrl} from './models/data-url';
import {DOC_ORIENTATION} from './models/DOC_ORIENTATION';
import {UploadResponse} from './models/upload-response';
 
export class ImageCompress {
    getOrientation(file: File): Promise<DOC_ORIENTATION> {
        return new Promise<DOC_ORIENTATION>((resolve, reject) => {
            try {
                const reader = new FileReader();
                reader.onload = () => {
                    const view = new DataView(reader.result as ArrayBuffer);
                    if (!view.byteLength) {
                        return resolve(DOC_ORIENTATION.NotDefined);
                    }
                    if (view.getUint16(0, false) !== 0xffd8) {
                        return resolve(DOC_ORIENTATION.NotDefined);
                    }
                    const length = view.byteLength;
                    let offset = 2;
                    while (offset < length) {
                        const marker = view.getUint16(offset, false);
                        offset += 2;
                        if (marker === 0xffe1) {
                            Iif (view.getUint32((offset += 2), false) !== 0x45786966) {
                                return resolve(DOC_ORIENTATION.NotJpeg);
                            }
                            const little = view.getUint16((offset += 6), false) === 0x4949;
                            offset += view.getUint32(offset + 4, little);
                            const tags = view.getUint16(offset, little);
                            offset += 2;
                            for (let i = 0; i < tags; i++) {
                                if (view.getUint16(offset + i * 12, little) === 0x0112) {
                                    return resolve(view.getUint16(offset + i * 12 + 8, little));
                                }
                            }
                        } else Iif ((marker & 0xff00) !== 0xff00) {
                            break;
                        } else {
                            offset += view.getUint16(offset, false);
                        }
                    }
                    return resolve(DOC_ORIENTATION.NotJpeg);
                };
                reader.readAsArrayBuffer(file);
            } catch (e) {
                return reject(DOC_ORIENTATION.Default);
            }
        });
    }
 
    uploadFile(render: Renderer2, multiple = true, rejectOnCancel = false): Promise<UploadResponse | UploadResponse[]> {
        return new Promise((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 => {
                    Iif (onlyNative) {
                        return this.generateUploadInputNative(window.document, multiple, rejectOnCancel);
                    } else {
                        return this.generateUploadInputRenderer(render, multiple, rejectOnCancel);
                    }
                })
                .then((filesList: FileList | null) => {
                    const files = filesList ? Array.from(filesList) : [];
                    const orientationPromises = files.map(file => this.getOrientation(file));
                    const readerPromises = files.map(file => this.fileToDataURL(file));
 
                    let orientationsResult: DOC_ORIENTATION[] = [];
 
                    Promise.all(orientationPromises)
                        .then((orientations: DOC_ORIENTATION[]) => {
                            orientationsResult = orientations;
                            return Promise.all(readerPromises);
                        })
                        .then(readerResult => {
                            const resultArray = readerResult.map((parsedFile, index) => ({
                                image: parsedFile.dataUrl,
                                orientation: orientationsResult[index],
                                fileName: parsedFile.fileName,
                            }));
 
                            if (multiple) {
                                resolve(resultArray);
                            } else {
                                resolve(resultArray[0]);
                            }
                        });
                })
                .catch(err => reject(err));
        });
    }
 
    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) => {
                //myReader.onloadend = (progressEvent: ProgressEvent<FileReader>)
                resolve({dataUrl: e.target.result, fileName: file.name});
            };
            try {
                reader.readAsDataURL(file);
            } catch (e) {
                reject(`ngx-image-compress - probably no file have been selected: ${e}`);
            }
        });
    }
 
    generateUploadInputRenderer(render: Renderer2, multiple = true, rejectOnCancel = false) {
        let lock = false;
        return new Promise<FileList | null>((resolve, reject) => {
            const inputElement = render.createElement('input');
            render.setStyle(inputElement, 'display', 'none');
            render.setProperty(inputElement, 'type', 'file');
            render.setProperty(inputElement, 'accept', 'image/*, .heic');
 
            if (multiple) {
                render.setProperty(inputElement, 'multiple', 'true');
            }
 
            render.listen(inputElement, 'click', ($event: MouseEvent) => {
                ($event.target as any as HTMLInputElement).value = '';
            });
 
            render.listen(inputElement, 'change', $event => {
                lock = true;
                const files: FileList = $event.target.files;
                resolve(files);
            });
 
            Iif (rejectOnCancel) {
                window.addEventListener(
                    'focus',
                    () => {
                        setTimeout(() => {
                            Iif (!lock) {
                                reject(new Error('file upload on blur - no file selected'));
                            }
                        }, 300);
                    },
                    {once: true}
                );
            }
 
            inputElement.click();
        });
    }
 
    generateUploadInputNative(documentNativeApi: any, multiple = true, rejectOnCancel = false) {
        let lock = false;
        return new Promise<FileList | null>((resolve, reject) => {
            const inputElement = documentNativeApi.createElement('input');
            inputElement.id = 'upload-input' + new Date();
            inputElement.style.display = 'none';
            inputElement.setAttribute('type', 'file');
            inputElement.setAttribute('accept', 'image/*, .heic');
 
            if (multiple) {
                inputElement.setAttribute('multiple', 'true');
            }
 
            documentNativeApi.body.appendChild(inputElement);
 
            inputElement.addEventListener(
                'change',
                () => {
                    lock = true;
                    resolve(inputElement.files);
                    documentNativeApi.body.removeChild(documentNativeApi.getElementById(inputElement.id) as Node);
                },
                {once: true}
            );
 
            Iif (rejectOnCancel) {
                window.addEventListener(
                    'focus',
                    () => {
                        setTimeout(() => {
                            Iif (!lock && documentNativeApi.getElementById(inputElement.id)) {
                                reject(new Error('file upload on blur - no file selected'));
                                documentNativeApi.body.removeChild(documentNativeApi.getElementById(inputElement.id) as Node);
                            }
                        }, 300);
                    },
                    {once: true}
                );
            }
 
            // open file select box
            inputElement.click();
        });
    }
 
    compress(
        imageDataUrlSource: DataUrl,
        orientation: DOC_ORIENTATION,
        render: Renderer2,
        ratio = 50,
        quality = 50,
        maxwidth = 0,
        maxheight = 0
    ): Promise<string> {
        return new Promise(function (resolve, reject) {
            quality = quality / 100;
            ratio = ratio / 100;
            const sourceImage = new Image();
 
            // important for safari: we need to wait for onload event
            sourceImage.onload = () => {
                const canvas: HTMLCanvasElement = render.createElement('canvas');
                const ctx: CanvasRenderingContext2D | null = canvas.getContext('2d');
 
                Iif (!ctx) {
                    return reject(`No canvas context available`);
                }
 
                let w = sourceImage.naturalWidth;
                let h = sourceImage.naturalHeight;
 
                if (!CSS.supports('image-orientation', 'from-image')) {
                    if (orientation === DOC_ORIENTATION.Right || orientation === DOC_ORIENTATION.Left) {
                        const t = w;
                        w = h;
                        h = t;
                    }
                }
 
                const xratio = maxwidth ? maxwidth / w : 1;
                const yratio = maxheight ? maxheight / h : 1;
                ratio = Math.min(ratio, xratio, yratio);
                canvas.width = w * ratio;
                canvas.height = h * ratio;
 
                const TO_RADIANS = Math.PI / 180;
 
                if (CSS.supports('image-orientation', 'from-image') || orientation === DOC_ORIENTATION.Up) {
                    ctx.drawImage(sourceImage, 0, 0, canvas.width, canvas.height);
                } else if (orientation === DOC_ORIENTATION.Right) {
                    ctx.save();
                    ctx.rotate(90 * TO_RADIANS);
                    ctx.translate(0, -canvas.width);
                    ctx.drawImage(sourceImage, 0, 0, canvas.height, canvas.width);
                    ctx.restore();
                } else if (orientation === DOC_ORIENTATION.Left) {
                    ctx.save();
                    ctx.rotate(-90 * TO_RADIANS);
                    ctx.translate(-canvas.width, 0);
                    ctx.drawImage(sourceImage, 0, 0, canvas.height, canvas.width);
                    ctx.restore();
                } else if (orientation === DOC_ORIENTATION.Down) {
                    ctx.save();
                    ctx.rotate(180 * TO_RADIANS);
                    ctx.translate(-canvas.width, -canvas.height);
                    ctx.drawImage(sourceImage, 0, 0, canvas.width, canvas.height);
                    ctx.restore();
                } else {
                    // no orientation value found - same as default UP
                    ctx.drawImage(sourceImage, 0, 0, canvas.width, canvas.height);
                }
 
                const mime = imageDataUrlSource.substr(5, imageDataUrlSource.split(';')[0].length - 5);
                // TODO test on mime
                const result = canvas.toDataURL(mime, quality);
 
                resolve(result);
            };
 
            sourceImage.onerror = e => reject(e);
            sourceImage.src = imageDataUrlSource;
        });
    }
 
    byteCount = (imgString: DataUrl): number => encodeURI(imgString).split(/%..|./).length - 1;
 
    async uploadGetImageMaxSize(maxSizeMb: number, debugMode: boolean, render: Renderer2, rejectOnCancel = false): Promise<UploadResponse> {
        if (debugMode) {
            console.debug('Ngxthis - Opening upload window');
        }
 
        const myFile: UploadResponse = (await this.uploadFile(render, false, rejectOnCancel)) as UploadResponse;
 
        return await this.getImageMaxSize(myFile, maxSizeMb, debugMode, render);
    }
 
    async getImageMaxSize(myFile: UploadResponse, maxSizeMb: number, debugMode: boolean, render: Renderer2): Promise<UploadResponse> {
        const MAX_TRIES = 10;
 
        const bytesToMB = (bytes: number) => (bytes / 1024 / 1024).toFixed(2);
 
        if (debugMode) {
            console.debug('Ngxthis - Opening upload window');
        }
 
        let compressedFile;
 
        for (let i = 0; i < MAX_TRIES; i++) {
            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(
                            'Ngxthis -',
                            "File can't be reduced at all - returning the original",
                            bytesToMB(previousSize),
                            'MB large'
                        );
                    }
                    throw {...myFile, image: compressedFile};
                } else E{
                    Iif (debugMode) {
                        console.debug(
                            'Ngxthis -',
                            "File can't be reduced more - returning the best we can, which is ",
                            bytesToMB(previousSize),
                            'MB large'
                        );
                    }
                    throw {...myFile, image: compressedFile};
                }
            } else {
                if (newSize < maxSizeMb * 1024 * 1024) {
                    if (debugMode) {
                        console.debug('Ngxthis -', 'Here your file', bytesToMB(newSize), 'MB large');
                    }
                    return {...myFile, image: compressedFile};
                } else IEif (i === 9) {
                    Iif (debugMode) {
                        console.debug(
                            'Ngxthis -',
                            "File can't reach the desired size after",
                            MAX_TRIES,
                            'tries. Returning file ',
                            bytesToMB(previousSize),
                            'MB large'
                        );
                    }
                    throw {...myFile, image: compressedFile};
                }
            }
            Iif (debugMode) {
                console.debug('Ngxthis -', 'Reached', bytesToMB(newSize), 'MB large. Trying another time after', i + 1, 'times');
            }
            myFile.image = compressedFile;
        }
        Iif (debugMode) {
            console.debug('Ngxthis - Unexpected error');
        }
        throw {};
    }
}