diff --git a/.babelrc b/.babelrc
new file mode 100644
index 0000000..1a103c4
--- /dev/null
+++ b/.babelrc
@@ -0,0 +1,5 @@
+{
+ "plugins": [
+ "@babel/plugin-transform-spread"
+ ]
+}
\ No newline at end of file
diff --git a/.eslintrc.js b/.eslintrc.js
new file mode 100644
index 0000000..a354160
--- /dev/null
+++ b/.eslintrc.js
@@ -0,0 +1,13 @@
+module.exports = {
+ parser: "babel-eslint",
+ parserOptions: {
+ ecmaVersion: 6,
+ sourceType: "module",
+ ecmaVersion: {
+ experimentalObjectRestSpread: true,
+ },
+ },
+ rules: {
+ semi: "error",
+ },
+};
diff --git a/.gitignore b/.gitignore
index 71b051e..c45f6cb 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,3 @@
npm-debug.log
node_modules/
+package-lock.json
diff --git a/dist/defaults.js b/dist/defaults.js
new file mode 100644
index 0000000..d03d842
--- /dev/null
+++ b/dist/defaults.js
@@ -0,0 +1,118 @@
+(function webpackUniversalModuleDefinition(root, factory) {
+ if(typeof exports === 'object' && typeof module === 'object')
+ module.exports = factory();
+ else if(typeof define === 'function' && define.amd)
+ define([], factory);
+ else {
+ var a = factory();
+ for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
+ }
+})(window, function() {
+return /******/ (function(modules) { // webpackBootstrap
+/******/ // The module cache
+/******/ var installedModules = {};
+/******/
+/******/ // The require function
+/******/ function __webpack_require__(moduleId) {
+/******/
+/******/ // Check if module is in cache
+/******/ if(installedModules[moduleId]) {
+/******/ return installedModules[moduleId].exports;
+/******/ }
+/******/ // Create a new module (and put it into the cache)
+/******/ var module = installedModules[moduleId] = {
+/******/ i: moduleId,
+/******/ l: false,
+/******/ exports: {}
+/******/ };
+/******/
+/******/ // Execute the module function
+/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
+/******/
+/******/ // Flag the module as loaded
+/******/ module.l = true;
+/******/
+/******/ // Return the exports of the module
+/******/ return module.exports;
+/******/ }
+/******/
+/******/
+/******/ // expose the modules object (__webpack_modules__)
+/******/ __webpack_require__.m = modules;
+/******/
+/******/ // expose the module cache
+/******/ __webpack_require__.c = installedModules;
+/******/
+/******/ // define getter function for harmony exports
+/******/ __webpack_require__.d = function(exports, name, getter) {
+/******/ if(!__webpack_require__.o(exports, name)) {
+/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
+/******/ }
+/******/ };
+/******/
+/******/ // define __esModule on exports
+/******/ __webpack_require__.r = function(exports) {
+/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
+/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
+/******/ }
+/******/ Object.defineProperty(exports, '__esModule', { value: true });
+/******/ };
+/******/
+/******/ // create a fake namespace object
+/******/ // mode & 1: value is a module id, require it
+/******/ // mode & 2: merge all properties of value into the ns
+/******/ // mode & 4: return value when already ns object
+/******/ // mode & 8|1: behave like require
+/******/ __webpack_require__.t = function(value, mode) {
+/******/ if(mode & 1) value = __webpack_require__(value);
+/******/ if(mode & 8) return value;
+/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
+/******/ var ns = Object.create(null);
+/******/ __webpack_require__.r(ns);
+/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
+/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
+/******/ return ns;
+/******/ };
+/******/
+/******/ // getDefaultExport function for compatibility with non-harmony modules
+/******/ __webpack_require__.n = function(module) {
+/******/ var getter = module && module.__esModule ?
+/******/ function getDefault() { return module['default']; } :
+/******/ function getModuleExports() { return module; };
+/******/ __webpack_require__.d(getter, 'a', getter);
+/******/ return getter;
+/******/ };
+/******/
+/******/ // Object.prototype.hasOwnProperty.call
+/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
+/******/
+/******/ // __webpack_public_path__
+/******/ __webpack_require__.p = "";
+/******/
+/******/
+/******/ // Load entry module and return exports
+/******/ return __webpack_require__(__webpack_require__.s = 1);
+/******/ })
+/************************************************************************/
+/******/ ([
+/* 0 */,
+/* 1 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony default export */ __webpack_exports__["default"] = ({
+ sizeLimit: 16777216,
+ // 16MB
+ maxWidth: 500,
+ maxHeight: 500,
+ quality: 0.5,
+ base64OutputType: false,
+ blobOutputType: true,
+ allowedFileTypes: ["jpg", "png", "jpeg"]
+});
+
+/***/ })
+/******/ ]);
+});
+//# sourceMappingURL=defaults.js.map
\ No newline at end of file
diff --git a/dist/defaults.js.map b/dist/defaults.js.map
new file mode 100644
index 0000000..12961a3
--- /dev/null
+++ b/dist/defaults.js.map
@@ -0,0 +1 @@
+{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///webpack/bootstrap","webpack:///./src/defaults.js"],"names":["sizeLimit","maxWidth","maxHeight","quality","base64OutputType","blobOutputType","allowedFileTypes"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,O;QCVA;QACA;;QAEA;QACA;;QAEA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;;QAEA;QACA;;QAEA;QACA;;QAEA;QACA;QACA;;;QAGA;QACA;;QAEA;QACA;;QAEA;QACA;QACA;QACA,0CAA0C,gCAAgC;QAC1E;QACA;;QAEA;QACA;QACA;QACA,wDAAwD,kBAAkB;QAC1E;QACA,iDAAiD,cAAc;QAC/D;;QAEA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA,yCAAyC,iCAAiC;QAC1E,gHAAgH,mBAAmB,EAAE;QACrI;QACA;;QAEA;QACA;QACA;QACA,2BAA2B,0BAA0B,EAAE;QACvD,iCAAiC,eAAe;QAChD;QACA;QACA;;QAEA;QACA,sDAAsD,+DAA+D;;QAErH;QACA;;;QAGA;QACA;;;;;;;;;AClFA;AAAe;AACbA,WAAS,EAAE,QADE;AACQ;AACrBC,UAAQ,EAAE,GAFG;AAGbC,WAAS,EAAE,GAHE;AAIbC,SAAO,EAAE,GAJI;AAKbC,kBAAgB,EAAE,KALL;AAMbC,gBAAc,EAAE,IANH;AAObC,kBAAgB,EAAE,CAAC,KAAD,EAAQ,KAAR,EAAe,MAAf;AAPL,CAAf,E","file":"./defaults.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse {\n\t\tvar a = factory();\n\t\tfor(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n\t}\n})(window, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 1);\n","export default {\n sizeLimit: 16777216, // 16MB\n maxWidth: 500,\n maxHeight: 500,\n quality: 0.5,\n base64OutputType: false,\n blobOutputType: true,\n allowedFileTypes: [\"jpg\", \"png\", \"jpeg\"],\n};\n"],"sourceRoot":""}
\ No newline at end of file
diff --git a/dist/index.js b/dist/index.js
new file mode 100644
index 0000000..9ebab25
--- /dev/null
+++ b/dist/index.js
@@ -0,0 +1,338 @@
+(function webpackUniversalModuleDefinition(root, factory) {
+ if(typeof exports === 'object' && typeof module === 'object')
+ module.exports = factory();
+ else if(typeof define === 'function' && define.amd)
+ define([], factory);
+ else {
+ var a = factory();
+ for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
+ }
+})(window, function() {
+return /******/ (function(modules) { // webpackBootstrap
+/******/ // The module cache
+/******/ var installedModules = {};
+/******/
+/******/ // The require function
+/******/ function __webpack_require__(moduleId) {
+/******/
+/******/ // Check if module is in cache
+/******/ if(installedModules[moduleId]) {
+/******/ return installedModules[moduleId].exports;
+/******/ }
+/******/ // Create a new module (and put it into the cache)
+/******/ var module = installedModules[moduleId] = {
+/******/ i: moduleId,
+/******/ l: false,
+/******/ exports: {}
+/******/ };
+/******/
+/******/ // Execute the module function
+/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
+/******/
+/******/ // Flag the module as loaded
+/******/ module.l = true;
+/******/
+/******/ // Return the exports of the module
+/******/ return module.exports;
+/******/ }
+/******/
+/******/
+/******/ // expose the modules object (__webpack_modules__)
+/******/ __webpack_require__.m = modules;
+/******/
+/******/ // expose the module cache
+/******/ __webpack_require__.c = installedModules;
+/******/
+/******/ // define getter function for harmony exports
+/******/ __webpack_require__.d = function(exports, name, getter) {
+/******/ if(!__webpack_require__.o(exports, name)) {
+/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
+/******/ }
+/******/ };
+/******/
+/******/ // define __esModule on exports
+/******/ __webpack_require__.r = function(exports) {
+/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
+/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
+/******/ }
+/******/ Object.defineProperty(exports, '__esModule', { value: true });
+/******/ };
+/******/
+/******/ // create a fake namespace object
+/******/ // mode & 1: value is a module id, require it
+/******/ // mode & 2: merge all properties of value into the ns
+/******/ // mode & 4: return value when already ns object
+/******/ // mode & 8|1: behave like require
+/******/ __webpack_require__.t = function(value, mode) {
+/******/ if(mode & 1) value = __webpack_require__(value);
+/******/ if(mode & 8) return value;
+/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
+/******/ var ns = Object.create(null);
+/******/ __webpack_require__.r(ns);
+/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
+/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
+/******/ return ns;
+/******/ };
+/******/
+/******/ // getDefaultExport function for compatibility with non-harmony modules
+/******/ __webpack_require__.n = function(module) {
+/******/ var getter = module && module.__esModule ?
+/******/ function getDefault() { return module['default']; } :
+/******/ function getModuleExports() { return module; };
+/******/ __webpack_require__.d(getter, 'a', getter);
+/******/ return getter;
+/******/ };
+/******/
+/******/ // Object.prototype.hasOwnProperty.call
+/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
+/******/
+/******/ // __webpack_public_path__
+/******/ __webpack_require__.p = "";
+/******/
+/******/
+/******/ // Load entry module and return exports
+/******/ return __webpack_require__(__webpack_require__.s = 3);
+/******/ })
+/************************************************************************/
+/******/ ([
+/* 0 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "validateFileType", function() { return validateFileType; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "validateFileSize", function() { return validateFileSize; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "base64ToBlob", function() { return base64ToBlob; });
+var validateFileType = function validateFileType(fileType, options) {
+ var accepted = false;
+ options.allowedFileTypes.forEach(function (allowedFileType) {
+ var regEx = new RegExp("image/" + allowedFileType);
+ if (regEx.test(fileType)) accepted = true;
+ });
+ return accepted;
+};
+var validateFileSize = function validateFileSize(imageSize, options) {
+ if (imageSize > options.sizeLimit) {
+ throw "Please upload an image of size less than " + options.sizeLimit / (1024 * 1024) + "MB";
+ }
+};
+var base64ToBlob = function base64ToBlob(base64, fileType) {
+ var sliceSize = 512; // uses 512 as packet size for efficient conversion
+
+ var regEx = new RegExp("^data:image/" + fileType + ";base64,");
+ base64 = base64.replace(regEx, "");
+ var byteCharacters = atob(base64);
+ var byteArrays = [];
+
+ for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
+ var slice = byteCharacters.slice(offset, offset + sliceSize);
+ var byteNumbers = new Array(slice.length);
+
+ for (var i = 0; i < slice.length; i++) {
+ byteNumbers[i] = slice.charCodeAt(i);
+ }
+
+ var byteArray = new Uint8Array(byteNumbers);
+ byteArrays.push(byteArray);
+ }
+
+ var blob = new Blob(byteArrays, {
+ type: "image/" + fileType
+ });
+ return blob;
+};
+
+/***/ }),
+/* 1 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony default export */ __webpack_exports__["default"] = ({
+ sizeLimit: 16777216,
+ // 16MB
+ maxWidth: 500,
+ maxHeight: 500,
+ quality: 0.5,
+ base64OutputType: false,
+ blobOutputType: true,
+ allowedFileTypes: ["jpg", "png", "jpeg"]
+});
+
+/***/ }),
+/* 2 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "resizeImageFile", function() { return resizeImageFile; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "resizeImageCanvas", function() { return resizeImageCanvas; });
+/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
+function _readOnlyError(name) { throw new Error("\"" + name + "\" is read-only"); }
+
+function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
+
+function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
+
+ // Returns a promise
+
+var resizeImageFile = /*#__PURE__*/function () {
+ var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(file, options) {
+ var reader;
+ return regeneratorRuntime.wrap(function _callee$(_context) {
+ while (1) {
+ switch (_context.prev = _context.next) {
+ case 0:
+ if (file) {
+ _context.next = 2;
+ break;
+ }
+
+ throw "File is null or undefined";
+
+ case 2:
+ if (Object(_utils__WEBPACK_IMPORTED_MODULE_0__["validateFileType"])(file.type, options)) {
+ _context.next = 4;
+ break;
+ }
+
+ throw "File " + file.name + " is not a supported image.";
+
+ case 4:
+ // read the files
+ reader = new FileReader();
+ reader.readAsArrayBuffer(file);
+
+ reader.onload = function (event) {
+ var blob = new Blob([event.target.result]); // create blob...
+
+ var imageSize = blob.size;
+ Object(_utils__WEBPACK_IMPORTED_MODULE_0__["validateFileSize"])(imageSize, options);
+ window.URL = window.URL || window.webkitURL;
+ var blobURL = window.URL.createObjectURL(blob); // and get it's URL
+ // helper Image object
+
+ var image = new Image();
+ image.src = blobURL;
+
+ image.onload = function () {
+ // have to wait till it's loaded
+ var resized = resizeImageCanvas(image, file.type, options); // send it to canvas
+
+ if (options.base64OutputType) {
+ return resized;
+ } else if (options.blobOutputType) {
+ return Object(_utils__WEBPACK_IMPORTED_MODULE_0__["base64ToBlob"])(resized, file.type);
+ }
+ };
+ };
+
+ case 7:
+ case "end":
+ return _context.stop();
+ }
+ }
+ }, _callee);
+ }));
+
+ return function resizeImageFile(_x, _x2) {
+ return _ref.apply(this, arguments);
+ };
+}();
+var resizeImageCanvas = function resizeImageCanvas(img, fileType, options) {
+ var canvas = document.createElement("canvas");
+ var width = img.width;
+ var height = img.height; // calculate the width and height, constraining the proportions
+
+ if (width > height) {
+ if (width > options.maxWidth) {
+ height = (_readOnlyError("height"), Math.round(height *= (_readOnlyError("height"), options.maxWidth / width)));
+ width = (_readOnlyError("width"), options.maxWidth);
+ }
+ } else {
+ if (height > options.maxHeight) {
+ width = (_readOnlyError("width"), Math.round(width *= (_readOnlyError("width"), options.maxHeight / height)));
+ height = (_readOnlyError("height"), options.maxHeight);
+ }
+ } // resize the canvas and draw the image data into it
+
+
+ canvas.width = width;
+ canvas.height = height;
+ var ctx = canvas.getContext("2d");
+ ctx.drawImage(img, 0, 0, width, height);
+ return canvas.toDataURL("image/" + fileType, options.quality);
+};
+
+/***/ }),
+/* 3 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony import */ var _defaults__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var _resizeImage__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
+function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
+
+function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
+
+function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
+
+
+
+
+var TransformImage = /*#__PURE__*/function () {
+ /*
+ Options - An object with following properties
+ sizeLimit : the byte size limit for the output file
+ maxWidth: the max width for the file in px
+ maxHeight: the max height for the file in px
+ quality: a value between 0 and 1 to denote the quality of the output image
+ base64OutputType: boolean to return a base64 string as the output
+ blobOutputType: boolean to return a blob as output
+ allowedFileTypes: allowed types for the image file e.g. PNG, JPEG, JPG
+ */
+ function TransformImage(options) {
+ _classCallCheck(this, TransformImage);
+
+ options.sizeLimit = options.sizeLimit || _defaults__WEBPACK_IMPORTED_MODULE_0__["default"].sizeLimit;
+ options.maxWidth = options.maxWidth || _defaults__WEBPACK_IMPORTED_MODULE_0__["default"].maxWidth;
+ options.maxHeight = options.maxHeight || _defaults__WEBPACK_IMPORTED_MODULE_0__["default"].maxHeight;
+ options.quality = options.quality || _defaults__WEBPACK_IMPORTED_MODULE_0__["default"].quality; // Quality - A value between 0 and 1 to denote the quality of the image in the output
+
+ options.base64OutputType = options.base64OutputType || _defaults__WEBPACK_IMPORTED_MODULE_0__["default"].base64OutputType; // return Base64 string
+
+ options.blobOutputType = options.blobOutputType || _defaults__WEBPACK_IMPORTED_MODULE_0__["default"].blobOutputType; // return Blob // NOTE: you can only choose one of the base64 or blob options
+
+ options.allowedFileTypes = options.allowedFileTypes || _defaults__WEBPACK_IMPORTED_MODULE_0__["default"].allowedFileTypes; // An array of allowed file types
+
+ this.options = options;
+ }
+ /*
+ @params
+ imageFile - The image file object obtained after user has uploaded the file
+ */
+
+
+ _createClass(TransformImage, [{
+ key: "resizeImage",
+ value: function resizeImage(imageFile) {
+ Object(_resizeImage__WEBPACK_IMPORTED_MODULE_1__["resizeImageFile"])(imageFile, _objectSpread({}, this.options));
+ }
+ }]);
+
+ return TransformImage;
+}();
+
+/* harmony default export */ __webpack_exports__["default"] = (TransformImage);
+
+/***/ })
+/******/ ]);
+});
+//# sourceMappingURL=index.js.map
\ No newline at end of file
diff --git a/dist/index.js.map b/dist/index.js.map
new file mode 100644
index 0000000..30633cb
--- /dev/null
+++ b/dist/index.js.map
@@ -0,0 +1 @@
+{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///webpack/bootstrap","webpack:///./src/utils.js","webpack:///./src/defaults.js","webpack:///./src/resizeImage.js","webpack:///./src/index.js"],"names":["validateFileType","fileType","options","accepted","allowedFileTypes","forEach","allowedFileType","regEx","RegExp","test","validateFileSize","imageSize","sizeLimit","base64ToBlob","base64","sliceSize","replace","byteCharacters","atob","byteArrays","offset","length","slice","byteNumbers","Array","i","charCodeAt","byteArray","Uint8Array","push","blob","Blob","type","maxWidth","maxHeight","quality","base64OutputType","blobOutputType","resizeImageFile","file","name","reader","FileReader","readAsArrayBuffer","onload","event","target","result","size","window","URL","webkitURL","blobURL","createObjectURL","image","Image","src","resized","resizeImageCanvas","img","canvas","document","createElement","width","height","Math","round","ctx","getContext","drawImage","toDataURL","TransformImage","defaultVal","imageFile"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,O;QCVA;QACA;;QAEA;QACA;;QAEA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;;QAEA;QACA;;QAEA;QACA;;QAEA;QACA;QACA;;;QAGA;QACA;;QAEA;QACA;;QAEA;QACA;QACA;QACA,0CAA0C,gCAAgC;QAC1E;QACA;;QAEA;QACA;QACA;QACA,wDAAwD,kBAAkB;QAC1E;QACA,iDAAiD,cAAc;QAC/D;;QAEA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA,yCAAyC,iCAAiC;QAC1E,gHAAgH,mBAAmB,EAAE;QACrI;QACA;;QAEA;QACA;QACA;QACA,2BAA2B,0BAA0B,EAAE;QACvD,iCAAiC,eAAe;QAChD;QACA;QACA;;QAEA;QACA,sDAAsD,+DAA+D;;QAErH;QACA;;;QAGA;QACA;;;;;;;;AClFA;AAAA;AAAA;AAAA;A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,iDAAU,CAACrC,OAAhD,CAJmB,CAIsC;;AACzDjC,WAAO,CAACkC,gBAAR,GACElC,OAAO,CAACkC,gBAAR,IAA4BoC,iDAAU,CAACpC,gBADzC,CALmB,CAMwC;;AAC3DlC,WAAO,CAACmC,cAAR,GACEnC,OAAO,CAACmC,cAAR,IAA0BmC,iDAAU,CAACnC,cADvC,CAPmB,CAQoC;;AACvDnC,WAAO,CAACE,gBAAR,GACEF,OAAO,CAACE,gBAAR,IAA4BoE,iDAAU,CAACpE,gBADzC,CATmB,CAUwC;;AAC3D,SAAKF,OAAL,GAAeA,OAAf;AACD;AAED;;;;;;;;gCAIYuE,S,EAAW;AACrBnC,0EAAe,CAACmC,SAAD,oBACV,KAAKvE,OADK,EAAf;AAGD;;;;;;AAGYqE,6EAAf,E","file":"./index.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse {\n\t\tvar a = factory();\n\t\tfor(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n\t}\n})(window, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 3);\n","export const validateFileType = (fileType, options) => {\n let accepted = false;\n options.allowedFileTypes.forEach((allowedFileType) => {\n const regEx = new RegExp(\"image/\" + allowedFileType);\n if (regEx.test(fileType)) accepted = true;\n });\n return accepted;\n};\n\nexport const validateFileSize = (imageSize, options) => {\n if (imageSize > options.sizeLimit) {\n throw (\n \"Please upload an image of size less than \" +\n options.sizeLimit / (1024 * 1024) +\n \"MB\"\n );\n }\n};\n\nexport const base64ToBlob = (base64, fileType) => {\n const sliceSize = 512; // uses 512 as packet size for efficient conversion\n const regEx = new RegExp(\"^data:image/\" + fileType + \";base64,\");\n base64 = base64.replace(regEx, \"\");\n const byteCharacters = atob(base64);\n const byteArrays = [];\n\n for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {\n const slice = byteCharacters.slice(offset, offset + sliceSize);\n\n const byteNumbers = new Array(slice.length);\n for (let i = 0; i < slice.length; i++) {\n byteNumbers[i] = slice.charCodeAt(i);\n }\n\n const byteArray = new Uint8Array(byteNumbers);\n\n byteArrays.push(byteArray);\n }\n\n const blob = new Blob(byteArrays, { type: \"image/\" + fileType });\n return blob;\n};\n","export default {\n sizeLimit: 16777216, // 16MB\n maxWidth: 500,\n maxHeight: 500,\n quality: 0.5,\n base64OutputType: false,\n blobOutputType: true,\n allowedFileTypes: [\"jpg\", \"png\", \"jpeg\"],\n};\n","import { validateFileType, validateFileSize, base64ToBlob } from \"./utils\";\n\n// Returns a promise\nexport const resizeImageFile = async (file, options) => {\n // Perform a null check on file\n if (!file) throw \"File is null or undefined\";\n\n // Validate the file type\n if (!validateFileType(file.type, options)) {\n throw \"File \" + file.name + \" is not a supported image.\";\n }\n\n // read the files\n const reader = new FileReader();\n\n reader.readAsArrayBuffer(file);\n\n reader.onload = (event) => {\n const blob = new Blob([event.target.result]); // create blob...\n const imageSize = blob.size;\n\n validateFileSize(imageSize, options);\n\n window.URL = window.URL || window.webkitURL;\n const blobURL = window.URL.createObjectURL(blob); // and get it's URL\n\n // helper Image object\n const image = new Image();\n image.src = blobURL;\n image.onload = function () {\n // have to wait till it's loaded\n const resized = resizeImageCanvas(image, file.type, options); // send it to canvas\n if (options.base64OutputType) {\n return resized;\n } else if (options.blobOutputType) {\n return base64ToBlob(resized, file.type);\n }\n };\n };\n};\n\nexport const resizeImageCanvas = (img, fileType, options) => {\n const canvas = document.createElement(\"canvas\");\n\n const width = img.width;\n const height = img.height;\n\n // calculate the width and height, constraining the proportions\n if (width > height) {\n if (width > options.maxWidth) {\n height = Math.round((height *= options.maxWidth / width));\n width = options.maxWidth;\n }\n } else {\n if (height > options.maxHeight) {\n width = Math.round((width *= options.maxHeight / height));\n height = options.maxHeight;\n }\n }\n\n // resize the canvas and draw the image data into it\n canvas.width = width;\n canvas.height = height;\n const ctx = canvas.getContext(\"2d\");\n ctx.drawImage(img, 0, 0, width, height);\n\n return canvas.toDataURL(\"image/\" + fileType, options.quality);\n};\n","import defaultVal from \"./defaults\";\nimport { resizeImageFile } from \"./resizeImage\";\n\nclass TransformImage {\n /*\n Options - An object with following properties\n sizeLimit : the byte size limit for the output file\n maxWidth: the max width for the file in px\n maxHeight: the max height for the file in px\n quality: a value between 0 and 1 to denote the quality of the output image\n base64OutputType: boolean to return a base64 string as the output\n blobOutputType: boolean to return a blob as output\n allowedFileTypes: allowed types for the image file e.g. PNG, JPEG, JPG\n */\n constructor(options) {\n options.sizeLimit = options.sizeLimit || defaultVal.sizeLimit;\n options.maxWidth = options.maxWidth || defaultVal.maxWidth;\n options.maxHeight = options.maxHeight || defaultVal.maxHeight;\n options.quality = options.quality || defaultVal.quality; // Quality - A value between 0 and 1 to denote the quality of the image in the output\n options.base64OutputType =\n options.base64OutputType || defaultVal.base64OutputType; // return Base64 string\n options.blobOutputType =\n options.blobOutputType || defaultVal.blobOutputType; // return Blob // NOTE: you can only choose one of the base64 or blob options\n options.allowedFileTypes =\n options.allowedFileTypes || defaultVal.allowedFileTypes; // An array of allowed file types\n this.options = options;\n }\n\n /*\n @params\n imageFile - The image file object obtained after user has uploaded the file\n */\n resizeImage(imageFile) {\n resizeImageFile(imageFile, {\n ...this.options,\n });\n }\n}\n\nexport default TransformImage;\n"],"sourceRoot":""}
\ No newline at end of file
diff --git a/dist/resizeImage.js b/dist/resizeImage.js
new file mode 100644
index 0000000..787441b
--- /dev/null
+++ b/dist/resizeImage.js
@@ -0,0 +1,254 @@
+(function webpackUniversalModuleDefinition(root, factory) {
+ if(typeof exports === 'object' && typeof module === 'object')
+ module.exports = factory();
+ else if(typeof define === 'function' && define.amd)
+ define([], factory);
+ else {
+ var a = factory();
+ for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
+ }
+})(window, function() {
+return /******/ (function(modules) { // webpackBootstrap
+/******/ // The module cache
+/******/ var installedModules = {};
+/******/
+/******/ // The require function
+/******/ function __webpack_require__(moduleId) {
+/******/
+/******/ // Check if module is in cache
+/******/ if(installedModules[moduleId]) {
+/******/ return installedModules[moduleId].exports;
+/******/ }
+/******/ // Create a new module (and put it into the cache)
+/******/ var module = installedModules[moduleId] = {
+/******/ i: moduleId,
+/******/ l: false,
+/******/ exports: {}
+/******/ };
+/******/
+/******/ // Execute the module function
+/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
+/******/
+/******/ // Flag the module as loaded
+/******/ module.l = true;
+/******/
+/******/ // Return the exports of the module
+/******/ return module.exports;
+/******/ }
+/******/
+/******/
+/******/ // expose the modules object (__webpack_modules__)
+/******/ __webpack_require__.m = modules;
+/******/
+/******/ // expose the module cache
+/******/ __webpack_require__.c = installedModules;
+/******/
+/******/ // define getter function for harmony exports
+/******/ __webpack_require__.d = function(exports, name, getter) {
+/******/ if(!__webpack_require__.o(exports, name)) {
+/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
+/******/ }
+/******/ };
+/******/
+/******/ // define __esModule on exports
+/******/ __webpack_require__.r = function(exports) {
+/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
+/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
+/******/ }
+/******/ Object.defineProperty(exports, '__esModule', { value: true });
+/******/ };
+/******/
+/******/ // create a fake namespace object
+/******/ // mode & 1: value is a module id, require it
+/******/ // mode & 2: merge all properties of value into the ns
+/******/ // mode & 4: return value when already ns object
+/******/ // mode & 8|1: behave like require
+/******/ __webpack_require__.t = function(value, mode) {
+/******/ if(mode & 1) value = __webpack_require__(value);
+/******/ if(mode & 8) return value;
+/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
+/******/ var ns = Object.create(null);
+/******/ __webpack_require__.r(ns);
+/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
+/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
+/******/ return ns;
+/******/ };
+/******/
+/******/ // getDefaultExport function for compatibility with non-harmony modules
+/******/ __webpack_require__.n = function(module) {
+/******/ var getter = module && module.__esModule ?
+/******/ function getDefault() { return module['default']; } :
+/******/ function getModuleExports() { return module; };
+/******/ __webpack_require__.d(getter, 'a', getter);
+/******/ return getter;
+/******/ };
+/******/
+/******/ // Object.prototype.hasOwnProperty.call
+/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
+/******/
+/******/ // __webpack_public_path__
+/******/ __webpack_require__.p = "";
+/******/
+/******/
+/******/ // Load entry module and return exports
+/******/ return __webpack_require__(__webpack_require__.s = 2);
+/******/ })
+/************************************************************************/
+/******/ ([
+/* 0 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "validateFileType", function() { return validateFileType; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "validateFileSize", function() { return validateFileSize; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "base64ToBlob", function() { return base64ToBlob; });
+var validateFileType = function validateFileType(fileType, options) {
+ var accepted = false;
+ options.allowedFileTypes.forEach(function (allowedFileType) {
+ var regEx = new RegExp("image/" + allowedFileType);
+ if (regEx.test(fileType)) accepted = true;
+ });
+ return accepted;
+};
+var validateFileSize = function validateFileSize(imageSize, options) {
+ if (imageSize > options.sizeLimit) {
+ throw "Please upload an image of size less than " + options.sizeLimit / (1024 * 1024) + "MB";
+ }
+};
+var base64ToBlob = function base64ToBlob(base64, fileType) {
+ var sliceSize = 512; // uses 512 as packet size for efficient conversion
+
+ var regEx = new RegExp("^data:image/" + fileType + ";base64,");
+ base64 = base64.replace(regEx, "");
+ var byteCharacters = atob(base64);
+ var byteArrays = [];
+
+ for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
+ var slice = byteCharacters.slice(offset, offset + sliceSize);
+ var byteNumbers = new Array(slice.length);
+
+ for (var i = 0; i < slice.length; i++) {
+ byteNumbers[i] = slice.charCodeAt(i);
+ }
+
+ var byteArray = new Uint8Array(byteNumbers);
+ byteArrays.push(byteArray);
+ }
+
+ var blob = new Blob(byteArrays, {
+ type: "image/" + fileType
+ });
+ return blob;
+};
+
+/***/ }),
+/* 1 */,
+/* 2 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "resizeImageFile", function() { return resizeImageFile; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "resizeImageCanvas", function() { return resizeImageCanvas; });
+/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
+function _readOnlyError(name) { throw new Error("\"" + name + "\" is read-only"); }
+
+function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
+
+function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
+
+ // Returns a promise
+
+var resizeImageFile = /*#__PURE__*/function () {
+ var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(file, options) {
+ var reader;
+ return regeneratorRuntime.wrap(function _callee$(_context) {
+ while (1) {
+ switch (_context.prev = _context.next) {
+ case 0:
+ if (file) {
+ _context.next = 2;
+ break;
+ }
+
+ throw "File is null or undefined";
+
+ case 2:
+ if (Object(_utils__WEBPACK_IMPORTED_MODULE_0__["validateFileType"])(file.type, options)) {
+ _context.next = 4;
+ break;
+ }
+
+ throw "File " + file.name + " is not a supported image.";
+
+ case 4:
+ // read the files
+ reader = new FileReader();
+ reader.readAsArrayBuffer(file);
+
+ reader.onload = function (event) {
+ var blob = new Blob([event.target.result]); // create blob...
+
+ var imageSize = blob.size;
+ Object(_utils__WEBPACK_IMPORTED_MODULE_0__["validateFileSize"])(imageSize, options);
+ window.URL = window.URL || window.webkitURL;
+ var blobURL = window.URL.createObjectURL(blob); // and get it's URL
+ // helper Image object
+
+ var image = new Image();
+ image.src = blobURL;
+
+ image.onload = function () {
+ // have to wait till it's loaded
+ var resized = resizeImageCanvas(image, file.type, options); // send it to canvas
+
+ if (options.base64OutputType) {
+ return resized;
+ } else if (options.blobOutputType) {
+ return Object(_utils__WEBPACK_IMPORTED_MODULE_0__["base64ToBlob"])(resized, file.type);
+ }
+ };
+ };
+
+ case 7:
+ case "end":
+ return _context.stop();
+ }
+ }
+ }, _callee);
+ }));
+
+ return function resizeImageFile(_x, _x2) {
+ return _ref.apply(this, arguments);
+ };
+}();
+var resizeImageCanvas = function resizeImageCanvas(img, fileType, options) {
+ var canvas = document.createElement("canvas");
+ var width = img.width;
+ var height = img.height; // calculate the width and height, constraining the proportions
+
+ if (width > height) {
+ if (width > options.maxWidth) {
+ height = (_readOnlyError("height"), Math.round(height *= (_readOnlyError("height"), options.maxWidth / width)));
+ width = (_readOnlyError("width"), options.maxWidth);
+ }
+ } else {
+ if (height > options.maxHeight) {
+ width = (_readOnlyError("width"), Math.round(width *= (_readOnlyError("width"), options.maxHeight / height)));
+ height = (_readOnlyError("height"), options.maxHeight);
+ }
+ } // resize the canvas and draw the image data into it
+
+
+ canvas.width = width;
+ canvas.height = height;
+ var ctx = canvas.getContext("2d");
+ ctx.drawImage(img, 0, 0, width, height);
+ return canvas.toDataURL("image/" + fileType, options.quality);
+};
+
+/***/ })
+/******/ ]);
+});
+//# sourceMappingURL=resizeImage.js.map
\ No newline at end of file
diff --git a/dist/resizeImage.js.map b/dist/resizeImage.js.map
new file mode 100644
index 0000000..0f07cc2
--- /dev/null
+++ b/dist/resizeImage.js.map
@@ -0,0 +1 @@
+{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///webpack/bootstrap","webpack:///./src/utils.js","webpack:///./src/resizeImage.js"],"names":["validateFileType","fileType","options","accepted","allowedFileTypes","forEach","allowedFileType","regEx","RegExp","test","validateFileSize","imageSize","sizeLimit","base64ToBlob","base64","sliceSize","replace","byteCharacters","atob","byteArrays","offset","length","slice","byteNumbers","Array","i","charCodeAt","byteArray","Uint8Array","push","blob","Blob","type","resizeImageFile","file","name","reader","FileReader","readAsArrayBuffer","onload","event","target","result","size","window","URL","webkitURL","blobURL","createObjectURL","image","Image","src","resized","resizeImageCanvas","base64OutputType","blobOutputType","img","canvas","document","createElement","width","height","maxWidth","Math","round","maxHeight","ctx","getContext","drawImage","toDataURL","quality"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,O;QCVA;QACA;;QAEA;QACA;;QAEA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;;QAEA;QACA;;QAEA;QACA;;QAEA;QACA;QACA;;;QAGA;QACA;;QAEA;QACA;;QAEA;QACA;QACA;QACA,0CAA0C,gCAAgC;QAC1E;QACA;;QAEA;QACA;QACA;QACA,wDAAwD,kBAAkB;QAC1E;QACA,iDAAiD,cAAc;QAC/D;;QAEA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA,yCAAyC,iCAAiC;QAC1E,gHAAgH,mBA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YH,MAAM,+BAAI3D,OAAO,CAAC4D,QAAR,GAAmBF,KAAvB,CAAlB,CAAH,CAAN;AACAA,WAAK,6BAAG1D,OAAO,CAAC4D,QAAX,CAAL;AACD;AACF,GALD,MAKO;AACL,QAAID,MAAM,GAAG3D,OAAO,CAAC+D,SAArB,EAAgC;AAC9BL,WAAK,6BAAGG,IAAI,CAACC,KAAL,CAAYJ,KAAK,8BAAI1D,OAAO,CAAC+D,SAAR,GAAoBJ,MAAxB,CAAjB,CAAH,CAAL;AACAA,YAAM,8BAAG3D,OAAO,CAAC+D,SAAX,CAAN;AACD;AACF,GAjB0D,CAmB3D;;;AACAR,QAAM,CAACG,KAAP,GAAeA,KAAf;AACAH,QAAM,CAACI,MAAP,GAAgBA,MAAhB;AACA,MAAMK,GAAG,GAAGT,MAAM,CAACU,UAAP,CAAkB,IAAlB,CAAZ;AACAD,KAAG,CAACE,SAAJ,CAAcZ,GAAd,EAAmB,CAAnB,EAAsB,CAAtB,EAAyBI,KAAzB,EAAgCC,MAAhC;AAEA,SAAOJ,MAAM,CAACY,SAAP,CAAiB,WAAWpE,QAA5B,EAAsCC,OAAO,CAACoE,OAA9C,CAAP;AACD,CA1BM,C","file":"./resizeImage.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse {\n\t\tvar a = factory();\n\t\tfor(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n\t}\n})(window, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 2);\n","export const validateFileType = (fileType, options) => {\n let accepted = false;\n options.allowedFileTypes.forEach((allowedFileType) => {\n const regEx = new RegExp(\"image/\" + allowedFileType);\n if (regEx.test(fileType)) accepted = true;\n });\n return accepted;\n};\n\nexport const validateFileSize = (imageSize, options) => {\n if (imageSize > options.sizeLimit) {\n throw (\n \"Please upload an image of size less than \" +\n options.sizeLimit / (1024 * 1024) +\n \"MB\"\n );\n }\n};\n\nexport const base64ToBlob = (base64, fileType) => {\n const sliceSize = 512; // uses 512 as packet size for efficient conversion\n const regEx = new RegExp(\"^data:image/\" + fileType + \";base64,\");\n base64 = base64.replace(regEx, \"\");\n const byteCharacters = atob(base64);\n const byteArrays = [];\n\n for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {\n const slice = byteCharacters.slice(offset, offset + sliceSize);\n\n const byteNumbers = new Array(slice.length);\n for (let i = 0; i < slice.length; i++) {\n byteNumbers[i] = slice.charCodeAt(i);\n }\n\n const byteArray = new Uint8Array(byteNumbers);\n\n byteArrays.push(byteArray);\n }\n\n const blob = new Blob(byteArrays, { type: \"image/\" + fileType });\n return blob;\n};\n","import { validateFileType, validateFileSize, base64ToBlob } from \"./utils\";\n\n// Returns a promise\nexport const resizeImageFile = async (file, options) => {\n // Perform a null check on file\n if (!file) throw \"File is null or undefined\";\n\n // Validate the file type\n if (!validateFileType(file.type, options)) {\n throw \"File \" + file.name + \" is not a supported image.\";\n }\n\n // read the files\n const reader = new FileReader();\n\n reader.readAsArrayBuffer(file);\n\n reader.onload = (event) => {\n const blob = new Blob([event.target.result]); // create blob...\n const imageSize = blob.size;\n\n validateFileSize(imageSize, options);\n\n window.URL = window.URL || window.webkitURL;\n const blobURL = window.URL.createObjectURL(blob); // and get it's URL\n\n // helper Image object\n const image = new Image();\n image.src = blobURL;\n image.onload = function () {\n // have to wait till it's loaded\n const resized = resizeImageCanvas(image, file.type, options); // send it to canvas\n if (options.base64OutputType) {\n return resized;\n } else if (options.blobOutputType) {\n return base64ToBlob(resized, file.type);\n }\n };\n };\n};\n\nexport const resizeImageCanvas = (img, fileType, options) => {\n const canvas = document.createElement(\"canvas\");\n\n const width = img.width;\n const height = img.height;\n\n // calculate the width and height, constraining the proportions\n if (width > height) {\n if (width > options.maxWidth) {\n height = Math.round((height *= options.maxWidth / width));\n width = options.maxWidth;\n }\n } else {\n if (height > options.maxHeight) {\n width = Math.round((width *= options.maxHeight / height));\n height = options.maxHeight;\n }\n }\n\n // resize the canvas and draw the image data into it\n canvas.width = width;\n canvas.height = height;\n const ctx = canvas.getContext(\"2d\");\n ctx.drawImage(img, 0, 0, width, height);\n\n return canvas.toDataURL(\"image/\" + fileType, options.quality);\n};\n"],"sourceRoot":""}
\ No newline at end of file
diff --git a/dist/utils.js b/dist/utils.js
new file mode 100644
index 0000000..cdd6c37
--- /dev/null
+++ b/dist/utils.js
@@ -0,0 +1,148 @@
+(function webpackUniversalModuleDefinition(root, factory) {
+ if(typeof exports === 'object' && typeof module === 'object')
+ module.exports = factory();
+ else if(typeof define === 'function' && define.amd)
+ define([], factory);
+ else {
+ var a = factory();
+ for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
+ }
+})(window, function() {
+return /******/ (function(modules) { // webpackBootstrap
+/******/ // The module cache
+/******/ var installedModules = {};
+/******/
+/******/ // The require function
+/******/ function __webpack_require__(moduleId) {
+/******/
+/******/ // Check if module is in cache
+/******/ if(installedModules[moduleId]) {
+/******/ return installedModules[moduleId].exports;
+/******/ }
+/******/ // Create a new module (and put it into the cache)
+/******/ var module = installedModules[moduleId] = {
+/******/ i: moduleId,
+/******/ l: false,
+/******/ exports: {}
+/******/ };
+/******/
+/******/ // Execute the module function
+/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
+/******/
+/******/ // Flag the module as loaded
+/******/ module.l = true;
+/******/
+/******/ // Return the exports of the module
+/******/ return module.exports;
+/******/ }
+/******/
+/******/
+/******/ // expose the modules object (__webpack_modules__)
+/******/ __webpack_require__.m = modules;
+/******/
+/******/ // expose the module cache
+/******/ __webpack_require__.c = installedModules;
+/******/
+/******/ // define getter function for harmony exports
+/******/ __webpack_require__.d = function(exports, name, getter) {
+/******/ if(!__webpack_require__.o(exports, name)) {
+/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
+/******/ }
+/******/ };
+/******/
+/******/ // define __esModule on exports
+/******/ __webpack_require__.r = function(exports) {
+/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
+/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
+/******/ }
+/******/ Object.defineProperty(exports, '__esModule', { value: true });
+/******/ };
+/******/
+/******/ // create a fake namespace object
+/******/ // mode & 1: value is a module id, require it
+/******/ // mode & 2: merge all properties of value into the ns
+/******/ // mode & 4: return value when already ns object
+/******/ // mode & 8|1: behave like require
+/******/ __webpack_require__.t = function(value, mode) {
+/******/ if(mode & 1) value = __webpack_require__(value);
+/******/ if(mode & 8) return value;
+/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
+/******/ var ns = Object.create(null);
+/******/ __webpack_require__.r(ns);
+/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
+/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
+/******/ return ns;
+/******/ };
+/******/
+/******/ // getDefaultExport function for compatibility with non-harmony modules
+/******/ __webpack_require__.n = function(module) {
+/******/ var getter = module && module.__esModule ?
+/******/ function getDefault() { return module['default']; } :
+/******/ function getModuleExports() { return module; };
+/******/ __webpack_require__.d(getter, 'a', getter);
+/******/ return getter;
+/******/ };
+/******/
+/******/ // Object.prototype.hasOwnProperty.call
+/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
+/******/
+/******/ // __webpack_public_path__
+/******/ __webpack_require__.p = "";
+/******/
+/******/
+/******/ // Load entry module and return exports
+/******/ return __webpack_require__(__webpack_require__.s = 0);
+/******/ })
+/************************************************************************/
+/******/ ([
+/* 0 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "validateFileType", function() { return validateFileType; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "validateFileSize", function() { return validateFileSize; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "base64ToBlob", function() { return base64ToBlob; });
+var validateFileType = function validateFileType(fileType, options) {
+ var accepted = false;
+ options.allowedFileTypes.forEach(function (allowedFileType) {
+ var regEx = new RegExp("image/" + allowedFileType);
+ if (regEx.test(fileType)) accepted = true;
+ });
+ return accepted;
+};
+var validateFileSize = function validateFileSize(imageSize, options) {
+ if (imageSize > options.sizeLimit) {
+ throw "Please upload an image of size less than " + options.sizeLimit / (1024 * 1024) + "MB";
+ }
+};
+var base64ToBlob = function base64ToBlob(base64, fileType) {
+ var sliceSize = 512; // uses 512 as packet size for efficient conversion
+
+ var regEx = new RegExp("^data:image/" + fileType + ";base64,");
+ base64 = base64.replace(regEx, "");
+ var byteCharacters = atob(base64);
+ var byteArrays = [];
+
+ for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
+ var slice = byteCharacters.slice(offset, offset + sliceSize);
+ var byteNumbers = new Array(slice.length);
+
+ for (var i = 0; i < slice.length; i++) {
+ byteNumbers[i] = slice.charCodeAt(i);
+ }
+
+ var byteArray = new Uint8Array(byteNumbers);
+ byteArrays.push(byteArray);
+ }
+
+ var blob = new Blob(byteArrays, {
+ type: "image/" + fileType
+ });
+ return blob;
+};
+
+/***/ })
+/******/ ]);
+});
+//# sourceMappingURL=utils.js.map
\ No newline at end of file
diff --git a/dist/utils.js.map b/dist/utils.js.map
new file mode 100644
index 0000000..2fe3b06
--- /dev/null
+++ b/dist/utils.js.map
@@ -0,0 +1 @@
+{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///webpack/bootstrap","webpack:///./src/utils.js"],"names":["validateFileType","fileType","options","accepted","allowedFileTypes","forEach","allowedFileType","regEx","RegExp","test","validateFileSize","imageSize","sizeLimit","base64ToBlob","base64","sliceSize","replace","byteCharacters","atob","byteArrays","offset","length","slice","byteNumbers","Array","i","charCodeAt","byteArray","Uint8Array","push","blob","Blob","type"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,O;QCVA;QACA;;QAEA;QACA;;QAEA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;;QAEA;QACA;;QAEA;QACA;;QAEA;QACA;QACA;;;QAGA;QACA;;QAEA;QACA;;QAEA;QACA;QACA;QACA,0CAA0C,gCAAgC;QAC1E;QACA;;QAEA;QACA;QACA;QACA,wDAAwD,kBAAkB;QAC1E;QACA,iDAAiD,cAAc;QAC/D;;QAEA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA,yCAAyC,iCAAiC;QAC1E,gHAAgH,mBAAmB,EAAE;QACrI;QACA;;QAEA;QACA;QACA;QACA,2BAA2B,0BAA0B,EAAE;QACvD,iCAAiC,eAAe;QAChD;QACA;QACA;;QAEA;QACA,sDAAsD,+DAA+D;;QAErH;QACA;;;QAGA;QACA;;;;;;;;AClFA;AAAA;AAAA;AAAA;AAAO,IAAMA,gBAAgB,GAAG,SAAnBA,gBAAmB,CAACC,QAAD,EAAWC,OAAX,EAAuB;AACrD,MAAIC,QAAQ,GAAG,KAAf;AACAD,SAAO,CAACE,gBAAR,CAAyBC,OAAzB,CAAiC,UAACC,eAAD,EAAqB;AACpD,QAAMC,KAAK,GAAG,IAAIC,MAAJ,CAAW,WAAWF,eAAtB,CAAd;AACA,QAAIC,KAAK,CAACE,IAAN,CAAWR,QAAX,CAAJ,EAA0BE,QAAQ,GAAG,IAAX;AAC3B,GAHD;AAIA,S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AqB;AAAEa,QAAI,EAAE,WAAW/B;AAAnB,GAArB,CAAb;AACA,SAAO6B,IAAP;AACD,CAtBM,C","file":"./utils.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse {\n\t\tvar a = factory();\n\t\tfor(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n\t}\n})(window, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 0);\n","export const validateFileType = (fileType, options) => {\n let accepted = false;\n options.allowedFileTypes.forEach((allowedFileType) => {\n const regEx = new RegExp(\"image/\" + allowedFileType);\n if (regEx.test(fileType)) accepted = true;\n });\n return accepted;\n};\n\nexport const validateFileSize = (imageSize, options) => {\n if (imageSize > options.sizeLimit) {\n throw (\n \"Please upload an image of size less than \" +\n options.sizeLimit / (1024 * 1024) +\n \"MB\"\n );\n }\n};\n\nexport const base64ToBlob = (base64, fileType) => {\n const sliceSize = 512; // uses 512 as packet size for efficient conversion\n const regEx = new RegExp(\"^data:image/\" + fileType + \";base64,\");\n base64 = base64.replace(regEx, \"\");\n const byteCharacters = atob(base64);\n const byteArrays = [];\n\n for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {\n const slice = byteCharacters.slice(offset, offset + sliceSize);\n\n const byteNumbers = new Array(slice.length);\n for (let i = 0; i < slice.length; i++) {\n byteNumbers[i] = slice.charCodeAt(i);\n }\n\n const byteArray = new Uint8Array(byteNumbers);\n\n byteArrays.push(byteArray);\n }\n\n const blob = new Blob(byteArrays, { type: \"image/\" + fileType });\n return blob;\n};\n"],"sourceRoot":""}
\ No newline at end of file
diff --git a/gulpfile.js b/gulpfile.js
new file mode 100644
index 0000000..72bf876
--- /dev/null
+++ b/gulpfile.js
@@ -0,0 +1,22 @@
+var gulp = require("gulp");
+var webpack = require("webpack");
+var genConfig = require("./webpack-gen-config.js");
+
+genConfig.webpackConfigs.forEach(function (configName) {
+ gulp.task(configName, function () {
+ return new Promise(function (resolve, reject) {
+ var webpackConfig = genConfig.generateConfig(configName);
+ webpack(webpackConfig, function (err, stats) {
+ if (err) {
+ return reject(err);
+ }
+ if (stats.hasErrors()) {
+ return reject(new Error(stats.compilation.errors.join("\n")));
+ }
+ resolve();
+ });
+ });
+ });
+});
+
+exports.build = gulp.series.apply(gulp.series, genConfig.webpackConfigs);
diff --git a/image-compressify.js b/image-compressify.js
deleted file mode 100644
index f5229df..0000000
--- a/image-compressify.js
+++ /dev/null
@@ -1,429 +0,0 @@
-////////////////---------- Upload Compress Image JS Plugin ---------------///////////////////
-
-// Author
-//---- Suman Anand
-
-var defaultVal = {
- url: "",
- sizeLimit: 16777216,
- maxWidth: 500,
- maxHeight: 500,
- quality: 0.5,
- outputType: "png",
- isBase64: false,
- allowFileType: ["jpg", "png", "jpeg"],
- enablePreview: false,
- inputFieldName: "avatar",
- autoSubmit: true,
- isDragNDrop: true,
- appendFileInput: true,
- fileInputSelector: "compressFileInput",
- allowMultiple: false,
- allowAjax: true,
- appendFormData: false
-};
-
-var uploadFile = function(options) {
- var self = this;
- this.url = options.url || defaultVal.url;
- this.sizeLimit = options.sizeLimit || defaultVal.sizeLimit;
- this.maxWidth = options.maxWidth || defaultVal.maxWidth;
- this.maxHeight = options.maxHeight || defaultVal.maxHeight;
- this.quality = options.quality || defaultVal.quality;
- this.outputType = options.outputType || defaultVal.outputType;
- this.isBase64 =
- typeof options.isBase64 === "undefined"
- ? defaultVal.isBase64
- : options.isBase64;
- this.allowFileType = options.allowFileType || defaultVal.allowFileType;
-
- this.enablePreview =
- typeof options.enablePreview === "undefined"
- ? defaultVal.enablePreview
- : options.enablePreview;
- // if enable preview is enabled then specify the preview Selector
- this.previewSelector = options.previewSelector;
-
- this.inputFieldName = options.inputFieldName || defaultVal.inputFieldName;
- this.autoSubmit =
- typeof options.autoSubmit === "undefined"
- ? defaultVal.autoSubmit
- : options.autoSubmit;
- this.isDragNDrop =
- typeof options.isDragNDrop === "undefined"
- ? defaultVal.isDragNDrop
- : options.isDragNDrop;
-
- this.appendFileInput =
- typeof options.appendFileInput === "undefined"
- ? defaultVal.appendFileInput
- : options.appendFileInput;
- // if append file input is set to false then specify the input selector
- this.fileInputSelector =
- options.fileInputSelector || defaultVal.fileInputSelector;
-
- this.allowMultiple =
- typeof options.allowMultiple === "undefined"
- ? defaultVal.allowMultiple
- : options.allowMultiple;
- // if allow multiple is set to true
- this.maxFiles = options.maxFiles;
-
- // allow ajax call to server
- this.allowAjax =
- typeof options.allowAjax === "undefined"
- ? defaultVal.allowAjax
- : options.allowAjax;
-
- this.appendFormData =
- typeof options.appendFormData === "undefined"
- ? defaultVal.appendFormData
- : options.appendFormData;
- //append formdata from form
- this.formID = options.formID;
- //append formdata from string ["param1=x¶m2=y"]
- this.formDataString = options.formDataString;
-
- // no op
- this.noop = function() {
- return;
- };
-
- this.onLoad = options.onLoad || this.noop;
- this.beforeSubmit = options.beforeSubmit || this.noop;
- this.onSuccess = options.onSuccess || this.noop;
- this.onFailure = options.onFailure || this.noop;
- this.targetElem = document.querySelector(options.selector);
- this.stopFlag = false;
- this.formDataArray = {};
- this.imageID = 0;
-
- self.formData = new FormData();
-
- // construct the input DOM
- var toAppend =
- 'Click here to uploadOr Drag n Drop the file
';
- this.toAppend = options.toAppend || toAppend;
- if (this.appendFileInput) {
- this.targetElem.insertAdjacentHTML("beforeend", this.toAppend);
- this.targetElem.style.position = "relative";
- }
- var fileInput = this.targetElem.querySelector("input[type=file]");
- fileInput.setAttribute("id", this.fileInputSelector);
-
- // read files
- this.readFiles = function(files) {
- for (var i = 0; i < files.length; i++) {
- this.processFile(files[i]); // process each file at once
- }
- var fileinput = document.getElementById(this.fileInputSelector);
- fileinput.value = "";
- };
-
- this.testFileType = function(fileType) {
- var accepted = false;
- for (var i = 0; i < this.allowFileType.length; i++) {
- var regEx = new RegExp("image/" + this.allowFileType[i]);
- if (regEx.test(fileType)) accepted = true;
- }
- return accepted;
- };
-
- this.processFile = function(file) {
- if (!this.testFileType(file.type)) {
- alert("File " + file.name + " is not an image.");
- return false;
- }
-
- // fire the onload callback
- this.onLoad();
-
- // read the files
- var reader = new FileReader();
-
- reader.readAsArrayBuffer(file);
-
- reader.onload = function(event) {
- // blob stuff
- var blob = new Blob([event.target.result]); // create blob...
- var imageSize = blob.size;
- // attach a 16 mb limit to images
- if (imageSize > this.sizeLimit) {
- alert(
- "Please upload an image of size less than " +
- this.sizeLimit / (1024 * 1024) +
- "MB"
- );
- }
- window.URL = window.URL || window.webkitURL;
- var blobURL = window.URL.createObjectURL(blob); // and get it's URL
-
- // helper Image object
- var image = new Image();
- image.src = blobURL;
- image.onload = function() {
- // have to wait till it's loaded
- var resized = self.resizeImg(image); // send it to canvas
- var resizedBlob;
-
- if (self.isBase64) {
- self.formData.append(
- self.inputFieldName + (self.allowMultiple ? "[]" : ""),
- resized
- );
- } else {
- resizedBlob = self.base64ToBlob(resized);
- if (resizedBlob.size > file.size) {
- resizedBlob = file;
- }
- self.formData.append(
- self.inputFieldName + (self.allowMultiple ? "[]" : ""),
- resizedBlob
- );
- }
-
- if (self.allowAjax) {
- if (self.autoSubmit) {
- self.submitFormData();
- } else {
- self.formDataArray[self.imageID] = self.isBase64
- ? resized
- : resizedBlob;
- self.imageID++;
- }
- } else {
- if (self.isBase64) {
- var hiddenInput = document.createElement("input");
- hiddenInput.setAttribute("type", "hidden");
- hiddenInput.setAttribute(
- "name",
- self.inputFieldName + (self.allowMultiple ? "[]" : "")
- );
- hiddenInput.setAttribute("value", resized);
- hiddenInput.setAttribute("id", "hidden" + self.imageID);
- self.targetElem.appendChild(hiddenInput);
- }
- }
- };
- };
- };
-
- this.appendImageData = function() {
- var keys = Object.keys(this.formDataArray);
- for (var i = 0; i < keys.length; i++) {
- this.formData.append(
- this.inputFieldName + (self.allowMultiple ? "[]" : ""),
- this.formDataArray[keys[i]]
- );
- }
- };
-
- this.appendUserFormData = function() {
- // serialize form data to get a string of form data
- if (typeof this.formID !== "undefined") {
- var formEl = document.querySelector(this.formID);
- var inputs = formEl.querySelectorAll("input");
- for (var i = 0; i < inputs.length; i++) {
- this.formData.append(
- inputs[i].getAttribute("name"),
- inputs[i].getAttribute("value")
- );
- }
- }
- };
-
- // post data function
- this.submitFormData = function() {
- if (this.stopFlag) return;
- if (this.appendFormData) this.appendUserFormData();
- this.beforeSubmit();
- $.ajax({
- url: this.url,
- data: this.formData,
- type: "POST",
- processData: false,
- contentType: false
- })
- .done(function(data) {
- self.onSuccess(data);
- })
- .fail(function() {
- self.onFailure();
- });
- };
-
- // starts the upload
- this.startUpload = function() {
- this.stopFlag = false;
- if (!this.allowAjax) {
- console.log("Ajax is set to false");
- return;
- }
- this.formData = new FormData();
- if (!this.autoSubmit) {
- this.appendImageData();
- this.submitFormData();
- } else {
- this.submitFormData();
- }
- };
-
- // stops the upload
- this.stopUpload = function() {
- this.stopFlag = true;
- };
-
- this.resizeImg = function(img) {
- var canvas = document.createElement("canvas");
-
- var width = img.width;
- var height = img.height;
-
- // calculate the width and height, constraining the proportions
- if (width > height) {
- if (width > this.maxWidth) {
- height = Math.round((height *= this.maxWidth / width));
- width = this.maxWidth;
- }
- } else {
- if (height > this.maxHeight) {
- width = Math.round((width *= this.maxHeight / height));
- height = this.maxHeight;
- }
- }
-
- // resize the canvas and draw the image data into it
- canvas.width = width;
- canvas.height = height;
- var ctx = canvas.getContext("2d");
- ctx.drawImage(img, 0, 0, width, height);
-
- if (this.enablePreview) {
- var parentDiv = document.createElement("div");
- parentDiv.setAttribute("class", "preview_container");
- var previewSelector = document.getElementById(
- this.previewSelector.substring(1)
- );
- parentDiv.appendChild(canvas);
- var button = document.createElement("button");
- button.innerHTML = "Delete";
- button.setAttribute("class", "delete_preview");
- button.setAttribute("data-id", this.imageID);
- parentDiv.appendChild(button);
- previewSelector.appendChild(parentDiv);
- }
-
- return canvas.toDataURL("image/" + this.outputType, this.quality); // get the data from canvas as 50% JPG (can be also PNG, etc.)
- };
-
- this.base64ToBlob = function(base64, contentType, sliceSize) {
- contentType = contentType || "";
- sliceSize = sliceSize || 512; // uses 512 as packet size for efficient conversion
- var regEx = new RegExp("^data:image/" + this.outputType + ";base64,");
- base64 = base64.replace(regEx, "");
- var byteCharacters = atob(base64);
- var byteArrays = [];
-
- for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
- var slice = byteCharacters.slice(offset, offset + sliceSize);
-
- var byteNumbers = new Array(slice.length);
- for (var i = 0; i < slice.length; i++) {
- byteNumbers[i] = slice.charCodeAt(i);
- }
-
- var byteArray = new Uint8Array(byteNumbers);
-
- byteArrays.push(byteArray);
- }
-
- var blob = new Blob(byteArrays, { type: "image/" + this.outputType });
- return blob;
- };
-
- // removes the upload Area container from dom
- this.removeField = function() {
- this.stopUpload();
- if (this.toAppend) {
- this.targetElem.innerHTML = "";
- }
- if (this.enablePreview) {
- document.querySelector(this.previewSelector).innerHTML = "";
- }
- };
-
- this.addListener = function(el, eventArr, callback) {
- for (var i = 0; i < eventArr.length; i++) {
- el.addEventListener(eventArr[i], callback);
- }
- };
-
- // read files from input
- document.querySelector("body").addEventListener("change", function(e) {
- if (e.target && e.target.matches("#" + this.fileInputSelector)) {
- if (
- !(window.File && window.FileReader && window.Filelist && window.Blob)
- ) {
- alert("The File APIs are not fully supported in this browser.");
- return false;
- }
- }
- self.readFiles(e.target.files);
- });
-
- // delete preview code
- document.querySelector("body").addEventListener("change", function(e) {
- if (e.target && e.target.matches(".delete_preview")) {
- e.target.parentNode.parentNode.removeChild(e.target.parentNode);
- delete self.formDataArray[e.target.getAttribute("data-id")];
- var hiddenEl = document.querySelector(
- "#hidden" + e.target.getAttribute("data-id")
- );
- hiddenEl.parentNode.removeChild(hiddenEl);
- var fileInput = document.getElementById(self.fileInputSelector);
- fileInput.value = "";
- }
- });
-
- if (this.isDragNDrop) {
- // code for drag and drop images
- // drag and drop feature integrated
- addListener(
- this.targetElem,
- [
- "drag",
- "dragstart",
- "dragend",
- "dragover",
- "dragenter",
- "dragleave",
- "drop"
- ],
- function(e) {
- e.preventDefault();
- e.stopPropagation();
- }
- );
-
- addListener(this.targetElem, ["dragover", "dragenter"], function() {
- self.targetElem.classList.add("is-dragover");
- });
-
- addListener(this.targetElem, ["dragleave", "dragend", "drop"], function() {
- self.targetElem.classList.remove("is-dragover");
- });
-
- this.targetElem.addEventListener("drop", function() {
- droppedFiles = e.originalEvent.dataTransfer.files;
- self.targetElem.classList.add("ajax-file-upload-statusbar");
- self.readFiles(droppedFiles);
- });
- }
-
- return this;
-};
-
-// export the utility class
-module.exports = uploadFile;
diff --git a/index.js b/index.js
new file mode 100644
index 0000000..94a4044
--- /dev/null
+++ b/index.js
@@ -0,0 +1 @@
+export { default as TransformImage } from "./src";
diff --git a/lib/transform-image-js.js b/lib/transform-image-js.js
new file mode 100644
index 0000000..71ca704
--- /dev/null
+++ b/lib/transform-image-js.js
@@ -0,0 +1,320 @@
+(function webpackUniversalModuleDefinition(root, factory) {
+ if(typeof exports === 'object' && typeof module === 'object')
+ module.exports = factory();
+ else if(typeof define === 'function' && define.amd)
+ define("transform-image-js", [], factory);
+ else if(typeof exports === 'object')
+ exports["transform-image-js"] = factory();
+ else
+ root["transform-image-js"] = factory();
+})(window, function() {
+return /******/ (function(modules) { // webpackBootstrap
+/******/ // The module cache
+/******/ var installedModules = {};
+/******/
+/******/ // The require function
+/******/ function __webpack_require__(moduleId) {
+/******/
+/******/ // Check if module is in cache
+/******/ if(installedModules[moduleId]) {
+/******/ return installedModules[moduleId].exports;
+/******/ }
+/******/ // Create a new module (and put it into the cache)
+/******/ var module = installedModules[moduleId] = {
+/******/ i: moduleId,
+/******/ l: false,
+/******/ exports: {}
+/******/ };
+/******/
+/******/ // Execute the module function
+/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
+/******/
+/******/ // Flag the module as loaded
+/******/ module.l = true;
+/******/
+/******/ // Return the exports of the module
+/******/ return module.exports;
+/******/ }
+/******/
+/******/
+/******/ // expose the modules object (__webpack_modules__)
+/******/ __webpack_require__.m = modules;
+/******/
+/******/ // expose the module cache
+/******/ __webpack_require__.c = installedModules;
+/******/
+/******/ // define getter function for harmony exports
+/******/ __webpack_require__.d = function(exports, name, getter) {
+/******/ if(!__webpack_require__.o(exports, name)) {
+/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
+/******/ }
+/******/ };
+/******/
+/******/ // define __esModule on exports
+/******/ __webpack_require__.r = function(exports) {
+/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
+/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
+/******/ }
+/******/ Object.defineProperty(exports, '__esModule', { value: true });
+/******/ };
+/******/
+/******/ // create a fake namespace object
+/******/ // mode & 1: value is a module id, require it
+/******/ // mode & 2: merge all properties of value into the ns
+/******/ // mode & 4: return value when already ns object
+/******/ // mode & 8|1: behave like require
+/******/ __webpack_require__.t = function(value, mode) {
+/******/ if(mode & 1) value = __webpack_require__(value);
+/******/ if(mode & 8) return value;
+/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
+/******/ var ns = Object.create(null);
+/******/ __webpack_require__.r(ns);
+/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
+/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
+/******/ return ns;
+/******/ };
+/******/
+/******/ // getDefaultExport function for compatibility with non-harmony modules
+/******/ __webpack_require__.n = function(module) {
+/******/ var getter = module && module.__esModule ?
+/******/ function getDefault() { return module['default']; } :
+/******/ function getModuleExports() { return module; };
+/******/ __webpack_require__.d(getter, 'a', getter);
+/******/ return getter;
+/******/ };
+/******/
+/******/ // Object.prototype.hasOwnProperty.call
+/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
+/******/
+/******/ // __webpack_public_path__
+/******/ __webpack_require__.p = "";
+/******/
+/******/
+/******/ // Load entry module and return exports
+/******/ return __webpack_require__(__webpack_require__.s = 0);
+/******/ })
+/************************************************************************/
+/******/ ([
+/* 0 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+// ESM COMPAT FLAG
+__webpack_require__.r(__webpack_exports__);
+
+// EXPORTS
+__webpack_require__.d(__webpack_exports__, "TransformImage", function() { return /* reexport */ src; });
+
+// CONCATENATED MODULE: ./src/defaults.js
+/* harmony default export */ var defaults = ({
+ sizeLimit: 16777216,
+ // 16MB
+ maxWidth: 500,
+ maxHeight: 500,
+ quality: 0.5,
+ base64OutputType: false,
+ blobOutputType: true,
+ allowedFileTypes: ["jpg", "png", "jpeg"]
+});
+// CONCATENATED MODULE: ./src/utils.js
+var validateFileType = function validateFileType(fileType, options) {
+ var accepted = false;
+ options.allowedFileTypes.forEach(function (allowedFileType) {
+ var regEx = new RegExp("image/" + allowedFileType);
+ if (regEx.test(fileType)) accepted = true;
+ });
+ return accepted;
+};
+var validateFileSize = function validateFileSize(imageSize, options) {
+ if (imageSize > options.sizeLimit) {
+ throw "Please upload an image of size less than " + options.sizeLimit / (1024 * 1024) + "MB";
+ }
+};
+var base64ToBlob = function base64ToBlob(base64, fileType) {
+ var sliceSize = 512; // uses 512 as packet size for efficient conversion
+
+ var regEx = new RegExp("^data:image/" + fileType + ";base64,");
+ base64 = base64.replace(regEx, "");
+ var byteCharacters = atob(base64);
+ var byteArrays = [];
+
+ for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
+ var slice = byteCharacters.slice(offset, offset + sliceSize);
+ var byteNumbers = new Array(slice.length);
+
+ for (var i = 0; i < slice.length; i++) {
+ byteNumbers[i] = slice.charCodeAt(i);
+ }
+
+ var byteArray = new Uint8Array(byteNumbers);
+ byteArrays.push(byteArray);
+ }
+
+ var blob = new Blob(byteArrays, {
+ type: "image/" + fileType
+ });
+ return blob;
+};
+// CONCATENATED MODULE: ./src/resizeImage.js
+function _readOnlyError(name) { throw new Error("\"" + name + "\" is read-only"); }
+
+function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
+
+function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
+
+ // Returns a promise
+
+var resizeImageFile = /*#__PURE__*/function () {
+ var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(file, options) {
+ var reader;
+ return regeneratorRuntime.wrap(function _callee$(_context) {
+ while (1) {
+ switch (_context.prev = _context.next) {
+ case 0:
+ if (file) {
+ _context.next = 2;
+ break;
+ }
+
+ throw "File is null or undefined";
+
+ case 2:
+ if (validateFileType(file.type, options)) {
+ _context.next = 4;
+ break;
+ }
+
+ throw "File " + file.name + " is not a supported image.";
+
+ case 4:
+ // read the files
+ reader = new FileReader();
+ reader.readAsArrayBuffer(file);
+
+ reader.onload = function (event) {
+ var blob = new Blob([event.target.result]); // create blob...
+
+ var imageSize = blob.size;
+ validateFileSize(imageSize, options);
+ window.URL = window.URL || window.webkitURL;
+ var blobURL = window.URL.createObjectURL(blob); // and get it's URL
+ // helper Image object
+
+ var image = new Image();
+ image.src = blobURL;
+
+ image.onload = function () {
+ // have to wait till it's loaded
+ var resized = resizeImageCanvas(image, file.type, options); // send it to canvas
+
+ if (options.base64OutputType) {
+ return resized;
+ } else if (options.blobOutputType) {
+ return base64ToBlob(resized, file.type);
+ }
+ };
+ };
+
+ case 7:
+ case "end":
+ return _context.stop();
+ }
+ }
+ }, _callee);
+ }));
+
+ return function resizeImageFile(_x, _x2) {
+ return _ref.apply(this, arguments);
+ };
+}();
+var resizeImageCanvas = function resizeImageCanvas(img, fileType, options) {
+ var canvas = document.createElement("canvas");
+ var width = img.width;
+ var height = img.height; // calculate the width and height, constraining the proportions
+
+ if (width > height) {
+ if (width > options.maxWidth) {
+ height = (_readOnlyError("height"), Math.round(height *= (_readOnlyError("height"), options.maxWidth / width)));
+ width = (_readOnlyError("width"), options.maxWidth);
+ }
+ } else {
+ if (height > options.maxHeight) {
+ width = (_readOnlyError("width"), Math.round(width *= (_readOnlyError("width"), options.maxHeight / height)));
+ height = (_readOnlyError("height"), options.maxHeight);
+ }
+ } // resize the canvas and draw the image data into it
+
+
+ canvas.width = width;
+ canvas.height = height;
+ var ctx = canvas.getContext("2d");
+ ctx.drawImage(img, 0, 0, width, height);
+ return canvas.toDataURL("image/" + fileType, options.quality);
+};
+// CONCATENATED MODULE: ./src/index.js
+function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
+
+function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
+
+function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
+
+
+
+
+var src_TransformImage = /*#__PURE__*/function () {
+ /*
+ Options - An object with following properties
+ sizeLimit : the byte size limit for the output file
+ maxWidth: the max width for the file in px
+ maxHeight: the max height for the file in px
+ quality: a value between 0 and 1 to denote the quality of the output image
+ base64OutputType: boolean to return a base64 string as the output
+ blobOutputType: boolean to return a blob as output
+ allowedFileTypes: allowed types for the image file e.g. PNG, JPEG, JPG
+ */
+ function TransformImage(options) {
+ _classCallCheck(this, TransformImage);
+
+ options.sizeLimit = options.sizeLimit || defaults.sizeLimit;
+ options.maxWidth = options.maxWidth || defaults.maxWidth;
+ options.maxHeight = options.maxHeight || defaults.maxHeight;
+ options.quality = options.quality || defaults.quality; // Quality - A value between 0 and 1 to denote the quality of the image in the output
+
+ options.base64OutputType = options.base64OutputType || defaults.base64OutputType; // return Base64 string
+
+ options.blobOutputType = options.blobOutputType || defaults.blobOutputType; // return Blob // NOTE: you can only choose one of the base64 or blob options
+
+ options.allowedFileTypes = options.allowedFileTypes || defaults.allowedFileTypes; // An array of allowed file types
+
+ this.options = options;
+ }
+ /*
+ @params
+ imageFile - The image file object obtained after user has uploaded the file
+ */
+
+
+ _createClass(TransformImage, [{
+ key: "resizeImage",
+ value: function resizeImage(imageFile) {
+ resizeImageFile(imageFile, _objectSpread({}, this.options));
+ }
+ }]);
+
+ return TransformImage;
+}();
+
+/* harmony default export */ var src = (src_TransformImage);
+// CONCATENATED MODULE: ./index.js
+
+
+/***/ })
+/******/ ]);
+});
+//# sourceMappingURL=transform-image-js.map
\ No newline at end of file
diff --git a/lib/transform-image-js.map b/lib/transform-image-js.map
new file mode 100644
index 0000000..fe6eeb3
--- /dev/null
+++ b/lib/transform-image-js.map
@@ -0,0 +1 @@
+{"version":3,"sources":["webpack://transform-image-js/webpack/universalModuleDefinition","webpack://transform-image-js/webpack/bootstrap","webpack://transform-image-js/./src/defaults.js","webpack://transform-image-js/./src/utils.js","webpack://transform-image-js/./src/resizeImage.js","webpack://transform-image-js/./src/index.js"],"names":["sizeLimit","maxWidth","maxHeight","quality","base64OutputType","blobOutputType","allowedFileTypes","validateFileType","fileType","options","accepted","forEach","allowedFileType","regEx","RegExp","test","validateFileSize","imageSize","base64ToBlob","base64","sliceSize","replace","byteCharacters","atob","byteArrays","offset","length","slice","byteNumbers","Array","i","charCodeAt","byteArray","Uint8Array","push","blob","Blob","type","resizeImageFile","file","name","reader","FileReader","readAsArrayBuffer","onload","event","target","result","size","window","URL","webkitURL","blobURL","createObjectURL","image","Image","src","resized","resizeImageCanvas","img","canvas","document","createElement","width","height","Math","round","ctx","getContext","drawImage","toDataURL","TransformImage","defaultVal","imageFile"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,O;QCVA;QACA;;QAEA;QACA;;QAEA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;;QAEA;QACA;;QAEA;QACA;;QAEA;QACA;QACA;;;QAGA;QACA;;QAEA;QACA;;QAEA;QACA;QACA;QACA,0CAA0C,gCAAgC;QAC1E;QACA;;QAEA;QACA;QACA;QACA,wDAAwD,kBAAkB;QAC1E;QACA,iDAAiD,cAAc;QAC/D;;QAEA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA,yCAAyC,iCAAiC;QAC1E,gHAAgH,mBAAmB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O,CAACP,SAAR,IAAqBsE,QAAU,CAACtE,SAApD;AACAO,WAAO,CAACN,OAAR,GAAkBM,OAAO,CAACN,OAAR,IAAmBqE,QAAU,CAACrE,OAAhD,CAJmB,CAIsC;;AACzDM,WAAO,CAACL,gBAAR,GACEK,OAAO,CAACL,gBAAR,IAA4BoE,QAAU,CAACpE,gBADzC,CALmB,CAMwC;;AAC3DK,WAAO,CAACJ,cAAR,GACEI,OAAO,CAACJ,cAAR,IAA0BmE,QAAU,CAACnE,cADvC,CAPmB,CAQoC;;AACvDI,WAAO,CAACH,gBAAR,GACEG,OAAO,CAACH,gBAAR,IAA4BkE,QAAU,CAAClE,gBADzC,CATmB,CAUwC;;AAC3D,SAAKG,OAAL,GAAeA,OAAf;AACD;AAED;;;;;;;;gCAIYgE,S,EAAW;AACrBnC,qBAAe,CAACmC,SAAD,oBACV,KAAKhE,OADK,EAAf;AAGD;;;;;;AAGY8D,0DAAf,E","file":"transform-image-js.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"transform-image-js\", [], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"transform-image-js\"] = factory();\n\telse\n\t\troot[\"transform-image-js\"] = factory();\n})(window, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 0);\n","export default {\n sizeLimit: 16777216, // 16MB\n maxWidth: 500,\n maxHeight: 500,\n quality: 0.5,\n base64OutputType: false,\n blobOutputType: true,\n allowedFileTypes: [\"jpg\", \"png\", \"jpeg\"],\n};\n","export const validateFileType = (fileType, options) => {\n let accepted = false;\n options.allowedFileTypes.forEach((allowedFileType) => {\n const regEx = new RegExp(\"image/\" + allowedFileType);\n if (regEx.test(fileType)) accepted = true;\n });\n return accepted;\n};\n\nexport const validateFileSize = (imageSize, options) => {\n if (imageSize > options.sizeLimit) {\n throw (\n \"Please upload an image of size less than \" +\n options.sizeLimit / (1024 * 1024) +\n \"MB\"\n );\n }\n};\n\nexport const base64ToBlob = (base64, fileType) => {\n const sliceSize = 512; // uses 512 as packet size for efficient conversion\n const regEx = new RegExp(\"^data:image/\" + fileType + \";base64,\");\n base64 = base64.replace(regEx, \"\");\n const byteCharacters = atob(base64);\n const byteArrays = [];\n\n for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {\n const slice = byteCharacters.slice(offset, offset + sliceSize);\n\n const byteNumbers = new Array(slice.length);\n for (let i = 0; i < slice.length; i++) {\n byteNumbers[i] = slice.charCodeAt(i);\n }\n\n const byteArray = new Uint8Array(byteNumbers);\n\n byteArrays.push(byteArray);\n }\n\n const blob = new Blob(byteArrays, { type: \"image/\" + fileType });\n return blob;\n};\n","import { validateFileType, validateFileSize, base64ToBlob } from \"./utils\";\n\n// Returns a promise\nexport const resizeImageFile = async (file, options) => {\n // Perform a null check on file\n if (!file) throw \"File is null or undefined\";\n\n // Validate the file type\n if (!validateFileType(file.type, options)) {\n throw \"File \" + file.name + \" is not a supported image.\";\n }\n\n // read the files\n const reader = new FileReader();\n\n reader.readAsArrayBuffer(file);\n\n reader.onload = (event) => {\n const blob = new Blob([event.target.result]); // create blob...\n const imageSize = blob.size;\n\n validateFileSize(imageSize, options);\n\n window.URL = window.URL || window.webkitURL;\n const blobURL = window.URL.createObjectURL(blob); // and get it's URL\n\n // helper Image object\n const image = new Image();\n image.src = blobURL;\n image.onload = function () {\n // have to wait till it's loaded\n const resized = resizeImageCanvas(image, file.type, options); // send it to canvas\n if (options.base64OutputType) {\n return resized;\n } else if (options.blobOutputType) {\n return base64ToBlob(resized, file.type);\n }\n };\n };\n};\n\nexport const resizeImageCanvas = (img, fileType, options) => {\n const canvas = document.createElement(\"canvas\");\n\n const width = img.width;\n const height = img.height;\n\n // calculate the width and height, constraining the proportions\n if (width > height) {\n if (width > options.maxWidth) {\n height = Math.round((height *= options.maxWidth / width));\n width = options.maxWidth;\n }\n } else {\n if (height > options.maxHeight) {\n width = Math.round((width *= options.maxHeight / height));\n height = options.maxHeight;\n }\n }\n\n // resize the canvas and draw the image data into it\n canvas.width = width;\n canvas.height = height;\n const ctx = canvas.getContext(\"2d\");\n ctx.drawImage(img, 0, 0, width, height);\n\n return canvas.toDataURL(\"image/\" + fileType, options.quality);\n};\n","import defaultVal from \"./defaults\";\nimport { resizeImageFile } from \"./resizeImage\";\n\nclass TransformImage {\n /*\n Options - An object with following properties\n sizeLimit : the byte size limit for the output file\n maxWidth: the max width for the file in px\n maxHeight: the max height for the file in px\n quality: a value between 0 and 1 to denote the quality of the output image\n base64OutputType: boolean to return a base64 string as the output\n blobOutputType: boolean to return a blob as output\n allowedFileTypes: allowed types for the image file e.g. PNG, JPEG, JPG\n */\n constructor(options) {\n options.sizeLimit = options.sizeLimit || defaultVal.sizeLimit;\n options.maxWidth = options.maxWidth || defaultVal.maxWidth;\n options.maxHeight = options.maxHeight || defaultVal.maxHeight;\n options.quality = options.quality || defaultVal.quality; // Quality - A value between 0 and 1 to denote the quality of the image in the output\n options.base64OutputType =\n options.base64OutputType || defaultVal.base64OutputType; // return Base64 string\n options.blobOutputType =\n options.blobOutputType || defaultVal.blobOutputType; // return Blob // NOTE: you can only choose one of the base64 or blob options\n options.allowedFileTypes =\n options.allowedFileTypes || defaultVal.allowedFileTypes; // An array of allowed file types\n this.options = options;\n }\n\n /*\n @params\n imageFile - The image file object obtained after user has uploaded the file\n */\n resizeImage(imageFile) {\n resizeImageFile(imageFile, {\n ...this.options,\n });\n }\n}\n\nexport default TransformImage;\n"],"sourceRoot":""}
\ No newline at end of file
diff --git a/lib/transform-image-js.min.js b/lib/transform-image-js.min.js
new file mode 100644
index 0000000..fb1d30a
--- /dev/null
+++ b/lib/transform-image-js.min.js
@@ -0,0 +1,2 @@
+!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("transform-image-js",[],t):"object"==typeof exports?exports["transform-image-js"]=t():e["transform-image-js"]=t()}(window,(function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)r.d(n,i,function(t){return e[t]}.bind(null,i));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=0)}([function(e,t,r){"use strict";r.r(t),r.d(t,"TransformImage",(function(){return y}));var n={sizeLimit:16777216,maxWidth:500,maxHeight:500,quality:.5,base64OutputType:!1,blobOutputType:!0,allowedFileTypes:["jpg","png","jpeg"]},i=function(e,t){var r=!1;return t.allowedFileTypes.forEach((function(t){new RegExp("image/"+t).test(e)&&(r=!0)})),r},o=function(e,t){if(e>t.sizeLimit)throw"Please upload an image of size less than "+t.sizeLimit/1048576+"MB"},a=function(e,t){var r=new RegExp("^data:image/"+t+";base64,");e=e.replace(r,"");for(var n=atob(e),i=[],o=0;oo?i>r.maxWidth&&(u("height"),o=Math.round(o*=(u("height"),r.maxWidth/i)),u("width"),i=r.maxWidth):o>r.maxHeight&&(u("width"),i=Math.round(i*=(u("width"),r.maxHeight/o)),u("height"),o=r.maxHeight),n.width=i,n.height=o,n.getContext("2d").drawImage(e,0,0,i,o),n.toDataURL("image/"+t,r.quality)};function p(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function s(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function d(e,t){for(var r=0;r {\n let accepted = false;\n options.allowedFileTypes.forEach((allowedFileType) => {\n const regEx = new RegExp(\"image/\" + allowedFileType);\n if (regEx.test(fileType)) accepted = true;\n });\n return accepted;\n};\n\nexport const validateFileSize = (imageSize, options) => {\n if (imageSize > options.sizeLimit) {\n throw (\n \"Please upload an image of size less than \" +\n options.sizeLimit / (1024 * 1024) +\n \"MB\"\n );\n }\n};\n\nexport const base64ToBlob = (base64, fileType) => {\n const sliceSize = 512; // uses 512 as packet size for efficient conversion\n const regEx = new RegExp(\"^data:image/\" + fileType + \";base64,\");\n base64 = base64.replace(regEx, \"\");\n const byteCharacters = atob(base64);\n const byteArrays = [];\n\n for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {\n const slice = byteCharacters.slice(offset, offset + sliceSize);\n\n const byteNumbers = new Array(slice.length);\n for (let i = 0; i < slice.length; i++) {\n byteNumbers[i] = slice.charCodeAt(i);\n }\n\n const byteArray = new Uint8Array(byteNumbers);\n\n byteArrays.push(byteArray);\n }\n\n const blob = new Blob(byteArrays, { type: \"image/\" + fileType });\n return blob;\n};\n","import { validateFileType, validateFileSize, base64ToBlob } from \"./utils\";\n\n// Returns a promise\nexport const resizeImageFile = async (file, options) => {\n // Perform a null check on file\n if (!file) throw \"File is null or undefined\";\n\n // Validate the file type\n if (!validateFileType(file.type, options)) {\n throw \"File \" + file.name + \" is not a supported image.\";\n }\n\n // read the files\n const reader = new FileReader();\n\n reader.readAsArrayBuffer(file);\n\n reader.onload = (event) => {\n const blob = new Blob([event.target.result]); // create blob...\n const imageSize = blob.size;\n\n validateFileSize(imageSize, options);\n\n window.URL = window.URL || window.webkitURL;\n const blobURL = window.URL.createObjectURL(blob); // and get it's URL\n\n // helper Image object\n const image = new Image();\n image.src = blobURL;\n image.onload = function () {\n // have to wait till it's loaded\n const resized = resizeImageCanvas(image, file.type, options); // send it to canvas\n if (options.base64OutputType) {\n return resized;\n } else if (options.blobOutputType) {\n return base64ToBlob(resized, file.type);\n }\n };\n };\n};\n\nexport const resizeImageCanvas = (img, fileType, options) => {\n const canvas = document.createElement(\"canvas\");\n\n const width = img.width;\n const height = img.height;\n\n // calculate the width and height, constraining the proportions\n if (width > height) {\n if (width > options.maxWidth) {\n height = Math.round((height *= options.maxWidth / width));\n width = options.maxWidth;\n }\n } else {\n if (height > options.maxHeight) {\n width = Math.round((width *= options.maxHeight / height));\n height = options.maxHeight;\n }\n }\n\n // resize the canvas and draw the image data into it\n canvas.width = width;\n canvas.height = height;\n const ctx = canvas.getContext(\"2d\");\n ctx.drawImage(img, 0, 0, width, height);\n\n return canvas.toDataURL(\"image/\" + fileType, options.quality);\n};\n","import defaultVal from \"./defaults\";\nimport { resizeImageFile } from \"./resizeImage\";\n\nclass TransformImage {\n /*\n Options - An object with following properties\n sizeLimit : the byte size limit for the output file\n maxWidth: the max width for the file in px\n maxHeight: the max height for the file in px\n quality: a value between 0 and 1 to denote the quality of the output image\n base64OutputType: boolean to return a base64 string as the output\n blobOutputType: boolean to return a blob as output\n allowedFileTypes: allowed types for the image file e.g. PNG, JPEG, JPG\n */\n constructor(options) {\n options.sizeLimit = options.sizeLimit || defaultVal.sizeLimit;\n options.maxWidth = options.maxWidth || defaultVal.maxWidth;\n options.maxHeight = options.maxHeight || defaultVal.maxHeight;\n options.quality = options.quality || defaultVal.quality; // Quality - A value between 0 and 1 to denote the quality of the image in the output\n options.base64OutputType =\n options.base64OutputType || defaultVal.base64OutputType; // return Base64 string\n options.blobOutputType =\n options.blobOutputType || defaultVal.blobOutputType; // return Blob // NOTE: you can only choose one of the base64 or blob options\n options.allowedFileTypes =\n options.allowedFileTypes || defaultVal.allowedFileTypes; // An array of allowed file types\n this.options = options;\n }\n\n /*\n @params\n imageFile - The image file object obtained after user has uploaded the file\n */\n resizeImage(imageFile) {\n resizeImageFile(imageFile, {\n ...this.options,\n });\n }\n}\n\nexport default TransformImage;\n"],"sourceRoot":""}
\ No newline at end of file
diff --git a/package.json b/package.json
index 3cac062..3806701 100644
--- a/package.json
+++ b/package.json
@@ -4,11 +4,11 @@
"description": "compress uploaded images on front end",
"main": "image-compressify.js",
"scripts": {
- "test": "echo \"Error: no test specified\" && exit 1"
+ "build": "gulp build"
},
"repository": {
"type": "git",
- "url": "https://github.com/shellophobia/UploadCompressImage"
+ "url": "https://github.com/shellophobia/transform-image-js.git"
},
"keywords": [
"compress",
@@ -26,5 +26,23 @@
"javascript"
],
"author": "Suman Anand",
- "license": "ISC"
+ "license": "MIT",
+ "devDependencies": {
+ "@babel/core": "^7.9.0",
+ "@babel/plugin-transform-spread": "^7.8.3",
+ "@babel/preset-env": "^7.9.5",
+ "babel-loader": "^8.1.0",
+ "babel-polyfill": "^6.26.0",
+ "gulp": "^4.0.2",
+ "webpack": "^4.42.1",
+ "webpack-cli": "^3.3.11"
+ },
+ "bugs": {
+ "url": "https://github.com/shellophobia/transform-image-js/issues"
+ },
+ "publishConfig": {
+ "registry": "https://npm.pkg.github.com/"
+ },
+ "jsdelivr": "dist/transform-image-js.min.js",
+ "unpkg": "dist/transform-image-js.min.js"
}
diff --git a/src/defaults.js b/src/defaults.js
new file mode 100644
index 0000000..1bdbfa4
--- /dev/null
+++ b/src/defaults.js
@@ -0,0 +1,9 @@
+export default {
+ sizeLimit: 16777216, // 16MB
+ maxWidth: 500,
+ maxHeight: 500,
+ quality: 0.5,
+ base64OutputType: false,
+ blobOutputType: true,
+ allowedFileTypes: ["jpg", "png", "jpeg"],
+};
diff --git a/src/index.js b/src/index.js
new file mode 100644
index 0000000..13880a5
--- /dev/null
+++ b/src/index.js
@@ -0,0 +1,40 @@
+import defaultVal from "./defaults";
+import { resizeImageFile } from "./resizeImage";
+
+class TransformImage {
+ /*
+ Options - An object with following properties
+ sizeLimit : the byte size limit for the output file
+ maxWidth: the max width for the file in px
+ maxHeight: the max height for the file in px
+ quality: a value between 0 and 1 to denote the quality of the output image
+ base64OutputType: boolean to return a base64 string as the output
+ blobOutputType: boolean to return a blob as output
+ allowedFileTypes: allowed types for the image file e.g. PNG, JPEG, JPG
+ */
+ constructor(options) {
+ options.sizeLimit = options.sizeLimit || defaultVal.sizeLimit;
+ options.maxWidth = options.maxWidth || defaultVal.maxWidth;
+ options.maxHeight = options.maxHeight || defaultVal.maxHeight;
+ options.quality = options.quality || defaultVal.quality; // Quality - A value between 0 and 1 to denote the quality of the image in the output
+ options.base64OutputType =
+ options.base64OutputType || defaultVal.base64OutputType; // return Base64 string
+ options.blobOutputType =
+ options.blobOutputType || defaultVal.blobOutputType; // return Blob // NOTE: you can only choose one of the base64 or blob options
+ options.allowedFileTypes =
+ options.allowedFileTypes || defaultVal.allowedFileTypes; // An array of allowed file types
+ this.options = options;
+ }
+
+ /*
+ @params
+ imageFile - The image file object obtained after user has uploaded the file
+ */
+ resizeImage(imageFile) {
+ resizeImageFile(imageFile, {
+ ...this.options,
+ });
+ }
+}
+
+export default TransformImage;
diff --git a/src/resizeImage.js b/src/resizeImage.js
new file mode 100644
index 0000000..1098d82
--- /dev/null
+++ b/src/resizeImage.js
@@ -0,0 +1,68 @@
+import { validateFileType, validateFileSize, base64ToBlob } from "./utils";
+
+// Returns a promise
+export const resizeImageFile = async (file, options) => {
+ // Perform a null check on file
+ if (!file) throw "File is null or undefined";
+
+ // Validate the file type
+ if (!validateFileType(file.type, options)) {
+ throw "File " + file.name + " is not a supported image.";
+ }
+
+ // read the files
+ const reader = new FileReader();
+
+ reader.readAsArrayBuffer(file);
+
+ reader.onload = (event) => {
+ const blob = new Blob([event.target.result]); // create blob...
+ const imageSize = blob.size;
+
+ validateFileSize(imageSize, options);
+
+ window.URL = window.URL || window.webkitURL;
+ const blobURL = window.URL.createObjectURL(blob); // and get it's URL
+
+ // helper Image object
+ const image = new Image();
+ image.src = blobURL;
+ image.onload = function () {
+ // have to wait till it's loaded
+ const resized = resizeImageCanvas(image, file.type, options); // send it to canvas
+ if (options.base64OutputType) {
+ return resized;
+ } else if (options.blobOutputType) {
+ return base64ToBlob(resized, file.type);
+ }
+ };
+ };
+};
+
+export const resizeImageCanvas = (img, fileType, options) => {
+ const canvas = document.createElement("canvas");
+
+ const width = img.width;
+ const height = img.height;
+
+ // calculate the width and height, constraining the proportions
+ if (width > height) {
+ if (width > options.maxWidth) {
+ height = Math.round((height *= options.maxWidth / width));
+ width = options.maxWidth;
+ }
+ } else {
+ if (height > options.maxHeight) {
+ width = Math.round((width *= options.maxHeight / height));
+ height = options.maxHeight;
+ }
+ }
+
+ // resize the canvas and draw the image data into it
+ canvas.width = width;
+ canvas.height = height;
+ const ctx = canvas.getContext("2d");
+ ctx.drawImage(img, 0, 0, width, height);
+
+ return canvas.toDataURL("image/" + fileType, options.quality);
+};
diff --git a/src/utils.js b/src/utils.js
new file mode 100644
index 0000000..d5f7159
--- /dev/null
+++ b/src/utils.js
@@ -0,0 +1,42 @@
+export const validateFileType = (fileType, options) => {
+ let accepted = false;
+ options.allowedFileTypes.forEach((allowedFileType) => {
+ const regEx = new RegExp("image/" + allowedFileType);
+ if (regEx.test(fileType)) accepted = true;
+ });
+ return accepted;
+};
+
+export const validateFileSize = (imageSize, options) => {
+ if (imageSize > options.sizeLimit) {
+ throw (
+ "Please upload an image of size less than " +
+ options.sizeLimit / (1024 * 1024) +
+ "MB"
+ );
+ }
+};
+
+export const base64ToBlob = (base64, fileType) => {
+ const sliceSize = 512; // uses 512 as packet size for efficient conversion
+ const regEx = new RegExp("^data:image/" + fileType + ";base64,");
+ base64 = base64.replace(regEx, "");
+ const byteCharacters = atob(base64);
+ const byteArrays = [];
+
+ for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
+ const slice = byteCharacters.slice(offset, offset + sliceSize);
+
+ const byteNumbers = new Array(slice.length);
+ for (let i = 0; i < slice.length; i++) {
+ byteNumbers[i] = slice.charCodeAt(i);
+ }
+
+ const byteArray = new Uint8Array(byteNumbers);
+
+ byteArrays.push(byteArray);
+ }
+
+ const blob = new Blob(byteArrays, { type: "image/" + fileType });
+ return blob;
+};
diff --git a/webpack-gen-config.js b/webpack-gen-config.js
new file mode 100644
index 0000000..ab11ebf
--- /dev/null
+++ b/webpack-gen-config.js
@@ -0,0 +1,69 @@
+var webpack = require('webpack');
+var path = require('path');
+var glob = require('glob');
+
+function generateConfig(name) {
+ var uglify = name.indexOf('min') > -1;
+ var transformAllFiles = name === 'transform-image-all-files';
+ var output = {
+ path: path.resolve(__dirname, 'dist/'),
+ filename: transformAllFiles ? '[name]' : name + '.js',
+ libraryTarget: 'umd',
+ umdNamedDefine: true,
+ };
+ if (!transformAllFiles) {
+ output.path = path.resolve(__dirname, 'lib/'),
+ output.sourceMapFilename = name + '.map';
+ output.library = 'transform-image-js',
+ }
+ var config = {
+ entry: transformAllFiles ? getEntries('./src/**/*.js') : './index.js',
+ output: output,
+ node: {
+ process: false
+ },
+ module: {
+ rules: [
+ {
+ test: /\.js$/,
+ exclude: /(node_modules|bower_components)/,
+ use: {
+ loader: 'babel-loader',
+ options: {
+ presets: ['@babel/preset-env']
+ }
+ }
+ }
+ ]
+ },
+ devtool: 'source-map',
+ optimization: {
+ minimize: uglify,
+ }
+ };
+
+ config.plugins = [
+ new webpack.DefinePlugin({
+ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
+ })
+ ];
+
+ return config;
+}
+
+function getEntries(pattern) {
+ const entries = {};
+
+ glob.sync(pattern).forEach((file) => {
+ entries[file.replace('src/', '')] = path.join(__dirname, file);
+ });
+
+ return entries;
+}
+
+var webpackConfigs = ['transform-image-js', 'transform-image-js.min', 'transform-image-all-files'];
+
+module.exports = {
+ generateConfig: generateConfig,
+ webpackConfigs: webpackConfigs
+};
\ No newline at end of file