UNPKG

infinity-forge

Version:
92 lines 3.32 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Compressor = void 0; var Compressor = /** @class */ (function () { function Compressor(file, options) { if (options === void 0) { options = {}; } this.aborted = false; if (!file || !/^image\/\w+/.test(file.type)) { throw new Error('The first argument must be an image File or Blob object.'); } this.file = file; this.options = options; this.image = new Image(); this.init(); } Compressor.prototype.init = function () { var _this = this; this.reader = new FileReader(); this.reader.onload = function () { _this.load(_this.reader.result); }; this.reader.readAsDataURL(this.file); }; Compressor.prototype.load = function (url) { var _this = this; this.image.onload = function () { _this.compress(); }; this.image.onerror = function () { _this.fail(new Error('Failed to load the image.')); }; this.image.src = url; }; Compressor.prototype.compress = function () { var _this = this; var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); if (!context) { return this.fail(new Error('Cannot get canvas context.')); } var _a = this.options, maxWidth = _a.maxWidth, maxHeight = _a.maxHeight, _b = _a.quality, quality = _b === void 0 ? 0.8 : _b, _c = _a.mimeType, mimeType = _c === void 0 ? 'image/jpeg' : _c, beforeDraw = _a.beforeDraw; var _d = this.image, width = _d.width, height = _d.height; var targetWidth = width; var targetHeight = height; if (maxWidth && width > maxWidth) { targetWidth = maxWidth; targetHeight = (maxWidth / width) * height; } if (maxHeight && targetHeight > maxHeight) { targetHeight = maxHeight; targetWidth = (maxHeight / height) * width; } canvas.width = targetWidth; canvas.height = targetHeight; if (typeof beforeDraw === 'function') { beforeDraw(context, canvas); } context.drawImage(this.image, 0, 0, targetWidth, targetHeight); canvas.toBlob(function (blob) { if (!blob) { return _this.fail(new Error('Compression failed.')); } if (_this.options.success) { _this.options.success(blob); } }, mimeType, quality); }; Compressor.prototype.abort = function () { if (this.aborted) return; this.aborted = true; if (this.reader) { this.reader.abort(); } else if (!this.image.complete) { this.image.onload = null; this.image.onerror = null; this.image.src = ''; // Cancel load } else { this.fail(new Error('The compression process has been aborted.')); } }; Compressor.prototype.fail = function (error) { if (this.options.error) { this.options.error(error); } }; return Compressor; }()); exports.Compressor = Compressor; //# sourceMappingURL=index.js.map