UNPKG

infinity-forge

Version:
65 lines 3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getCropPreview = getCropPreview; exports.applyCrop = applyCrop; var ui_1 = require("../../../../../../../ui/index.js"); function getCropPreview(file, cropArea, maxSize) { if (maxSize === void 0) { maxSize = 300; } return new Promise(function (resolve, reject) { var img = new Image(); img.crossOrigin = 'anonymous'; img.onload = function () { var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); if (!ctx) { reject(new Error('Could not get canvas context')); return; } var aspectRatio = cropArea.width / cropArea.height; var previewWidth = maxSize; var previewHeight = maxSize / aspectRatio; if (previewHeight > maxSize) { previewHeight = maxSize; previewWidth = maxSize * aspectRatio; } canvas.width = previewWidth; canvas.height = previewHeight; ctx.drawImage(img, cropArea.x, cropArea.y, cropArea.width, cropArea.height, 0, 0, previewWidth, previewHeight); resolve(canvas.toDataURL('image/png')); }; img.src = (file === null || file === void 0 ? void 0 : file.url) || ''; }); } function applyCrop(file, cropArea, format, quality) { if (format === void 0) { format = 'png'; } if (quality === void 0) { quality = 0.9; } return new Promise(function (resolve, reject) { var img = new Image(); img.crossOrigin = 'anonymous'; img.onload = function () { var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); if (!ctx) { reject(new Error('Could not get canvas context')); return; } canvas.width = cropArea.width; canvas.height = cropArea.height; ctx.drawImage(img, cropArea.x, cropArea.y, cropArea.width, cropArea.height, 0, 0, cropArea.width, cropArea.height); canvas.toBlob(function (blob) { if (!blob) { reject(new Error('Failed to create blob')); return; } var fileName = file.title || file.fileName || 'cropped-image'; var fileExtension = format === 'jpg' ? 'jpg' : format; var croppedFileName = "".concat(fileName.replace(/\.[^/.]+$/, ''), "-cropped.").concat(fileExtension); var croppedFile = new File([blob], croppedFileName, { type: "image/".concat(format) }); var croppedFileSystem = (0, ui_1.convertToFileSystemType)(croppedFile); resolve(croppedFileSystem); }, "image/".concat(format), quality); }; img.src = (file === null || file === void 0 ? void 0 : file.url) || ''; }); } //# sourceMappingURL=crop-utils.js.map