@jysd/lrz
Version:
前端本地客户端压缩图片,兼容IOS,Android,PC、自动按需加载文件
1,397 lines (1,193 loc) • 79.9 kB
JavaScript
(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];
}
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // install a JSONP callback for chunk loading
/******/ var parentJsonpFunction = window["webpackJsonp"];
/******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules) {
/******/ // add "moreModules" to the modules object,
/******/ // then flag all "chunkIds" as loaded and fire callback
/******/ var moduleId, chunkId, i = 0, callbacks = [];
/******/ for(;i < chunkIds.length; i++) {
/******/ chunkId = chunkIds[i];
/******/ if(installedChunks[chunkId])
/******/ callbacks.push.apply(callbacks, installedChunks[chunkId]);
/******/ installedChunks[chunkId] = 0;
/******/ }
/******/ for(moduleId in moreModules) {
/******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {
/******/ modules[moduleId] = moreModules[moduleId];
/******/ }
/******/ }
/******/ if(parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules);
/******/ while(callbacks.length)
/******/ callbacks.shift().call(null, __webpack_require__);
/******/ };
/******/ // The module cache
/******/ var installedModules = {};
/******/ // object to store loaded and loading chunks
/******/ // "0" means "already loaded"
/******/ // Array means "loading", array contains callbacks
/******/ var installedChunks = {
/******/ 0:0
/******/ };
/******/ // 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] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // This file contains only the entry chunk.
/******/ // The chunk loading function for additional chunks
/******/ __webpack_require__.e = function requireEnsure(chunkId, callback) {
/******/ // "0" is the signal for "already loaded"
/******/ if(installedChunks[chunkId] === 0)
/******/ return callback.call(null, __webpack_require__);
/******/ // an array means "currently loading".
/******/ if(installedChunks[chunkId] !== undefined) {
/******/ installedChunks[chunkId].push(callback);
/******/ } else {
/******/ // start chunk loading
/******/ installedChunks[chunkId] = [callback];
/******/ var head = document.getElementsByTagName('head')[0];
/******/ var script = document.createElement('script');
/******/ script.type = 'text/javascript';
/******/ script.charset = 'utf-8';
/******/ script.async = true;
/******/ script.src = __webpack_require__.p + "" + ({}[chunkId]||chunkId) + ".chunk.js";
/******/ head.appendChild(script);
/******/ }
/******/ };
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
// 保证按需加载的文件路径正确
__webpack_require__.p = getJsDir('lrz') + '/';
window.URL = window.URL || window.webkitURL;
__webpack_require__(1);
var Promise = __webpack_require__(2),
BlobFormDataShim = __webpack_require__(6),
exif = __webpack_require__(7);
var UA = (function (userAgent) {
var ISOldIOS = /OS (\d)_.* like Mac OS X/g.exec(userAgent),
isOldAndroid = /Android (\d.*?);/g.exec(userAgent) || /Android\/(\d.*?) /g.exec(userAgent);
// 判断设备是否是IOS7以下
// 判断设备是否是android4.5以下
// 判断是否iOS
// 判断是否android
// 判断是否QQ浏览器
return {
oldIOS : ISOldIOS ? +ISOldIOS.pop() < 8 : false,
oldAndroid: isOldAndroid ? +isOldAndroid.pop().substr(0, 3) < 4.5 : false,
iOS : /\(i[^;]+;( U;)? CPU.+Mac OS X/.test(userAgent),
android : /Android/g.test(userAgent),
mQQBrowser: /MQQBrowser/g.test(userAgent)
}
})(navigator.userAgent);
function Lrz (file, opts) {
var that = this;
if (!file) throw new Error('没有收到图片,可能的解决方案:https://github.com/think2011/localResizeIMG/issues/7');
opts = opts || {};
that.defaults = {
width : null,
height : null,
fieldName: 'file',
quality : 0.7
};
that.file = file;
for (var p in opts) {
if (!opts.hasOwnProperty(p)) continue;
that.defaults[p] = opts[p];
}
return this.init();
}
Lrz.prototype.init = function () {
var that = this,
file = that.file,
fileIsString = typeof file === 'string',
fileIsBase64 = /^data:/.test(file),
img = new Image(),
canvas = document.createElement('canvas'),
blob = fileIsString ? file : URL.createObjectURL(file);
that.img = img;
that.blob = blob;
that.canvas = canvas;
if (fileIsString) {
that.fileName = fileIsBase64 ? 'base64.jpg' : (file.split('/').pop());
} else {
that.fileName = file.name;
}
if (!document.createElement('canvas').getContext) {
throw new Error('浏览器不支持canvas');
}
return new Promise(function (resolve, reject) {
img.onerror = function () {
var err = new Error('加载图片文件失败');
reject(err);
throw err;
};
img.onload = function () {
that._getBase64()
.then(function (base64) {
if (base64.length < 10) {
var err = new Error('生成base64失败');
reject(err);
throw err;
}
return base64;
})
.then(function (base64) {
var formData = null;
// 压缩文件太大就采用源文件,且使用原生的FormData() @source #55
if (typeof that.file === 'object' && base64.length > that.file.size) {
formData = new FormData();
file = that.file;
} else {
formData = new BlobFormDataShim.FormData();
file = dataURItoBlob(base64);
}
formData.append(that.defaults.fieldName, file, (that.fileName.replace(/\..+/g, '.jpg')));
resolve({
formData : formData,
fileLen : +file.size,
base64 : base64,
base64Len: base64.length,
origin : that.file,
file : file
});
// 释放内存
for (var p in that) {
if (!that.hasOwnProperty(p)) continue;
that[p] = null;
}
URL.revokeObjectURL(that.blob);
});
};
// 如果传入的是base64在移动端会报错
!fileIsBase64 && (img.crossOrigin = "*");
img.src = blob;
});
};
function exiforientation() {
return Modernizr && Modernizr.exiforientation || false
}
Lrz.prototype._getBase64 = function () {
var that = this,
img = that.img,
file = that.file,
canvas = that.canvas;
return new Promise(function (resolve) {
try {
// 传入blob在android4.3以下有bug
exif.getData(typeof file === 'object' ? file : img, function () {
that.orientation = exif.getTag(this, "Orientation");
that.resize = that._getResize();
that.ctx = canvas.getContext('2d');
canvas.width = that.resize.width;
canvas.height = that.resize.height;
// 设置为白色背景,jpg是不支持透明的,所以会被默认为canvas默认的黑色背景。
that.ctx.fillStyle = '#fff';
that.ctx.fillRect(0, 0, canvas.width, canvas.height);
// 根据设备对应处理方式
if (UA.oldIOS) {
that._createBase64ForOldIOS().then(resolve);
}
else {
that._createBase64().then(resolve);
}
});
} catch (err) {
// 这样能解决低内存设备闪退的问题吗?
throw new Error(err);
}
});
};
Lrz.prototype._createBase64ForOldIOS = function () {
var that = this,
img = that.img,
canvas = that.canvas,
defaults = that.defaults,
orientation = that.orientation;
return new Promise(function (resolve) {
__webpack_require__.e/* require */(1, function(__webpack_require__) { var __WEBPACK_AMD_REQUIRE_ARRAY__ = [__webpack_require__(8)]; (function (MegaPixImage) {
var mpImg = new MegaPixImage(img);
if ("5678".indexOf(orientation) > -1) {
mpImg.render(canvas, {
width : canvas.height,
height : canvas.width,
orientation: orientation
});
} else {
mpImg.render(canvas, {
width : canvas.width,
height : canvas.height,
orientation: orientation
});
}
resolve(canvas.toDataURL('image/jpeg', defaults.quality));
}.apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__));});
});
};
Lrz.prototype._createBase64 = function () {
var that = this,
resize = that.resize,
img = that.img,
canvas = that.canvas,
ctx = that.ctx,
defaults = that.defaults,
orientation = that.orientation;
// 调整为正确方向
if(exiforientation()) {
ctx.drawImage(img, 0, 0, resize.width, resize.height);
} else {
switch (orientation) {
case 3:
ctx.rotate(180 * Math.PI / 180);
ctx.drawImage(img, -resize.width, -resize.height, resize.width, resize.height);
break;
case 6:
ctx.rotate(90 * Math.PI / 180);
ctx.drawImage(img, 0, -resize.width, resize.height, resize.width);
break;
case 8:
ctx.rotate(270 * Math.PI / 180);
ctx.drawImage(img, -resize.height, 0, resize.height, resize.width);
break;
case 2:
ctx.translate(resize.width, 0);
ctx.scale(-1, 1);
ctx.drawImage(img, 0, 0, resize.width, resize.height);
break;
case 4:
ctx.translate(resize.width, 0);
ctx.scale(-1, 1);
ctx.rotate(180 * Math.PI / 180);
ctx.drawImage(img, -resize.width, -resize.height, resize.width, resize.height);
break;
case 5:
ctx.translate(resize.width, 0);
ctx.scale(-1, 1);
ctx.rotate(90 * Math.PI / 180);
ctx.drawImage(img, 0, -resize.width, resize.height, resize.width);
break;
case 7:
ctx.translate(resize.width, 0);
ctx.scale(-1, 1);
ctx.rotate(270 * Math.PI / 180);
ctx.drawImage(img, -resize.height, 0, resize.height, resize.width);
break;
}
}
return new Promise(function (resolve) {
if (UA.oldAndroid || UA.mQQBrowser || !navigator.userAgent) {
__webpack_require__.e/* require */(2, function(__webpack_require__) { var __WEBPACK_AMD_REQUIRE_ARRAY__ = [__webpack_require__(9)]; (function (JPEGEncoder) {
var encoder = new JPEGEncoder(),
img = ctx.getImageData(0, 0, canvas.width, canvas.height);
resolve(encoder.encode(img, defaults.quality * 100));
}.apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__));})
}
else {
resolve(canvas.toDataURL('image/jpeg', defaults.quality));
}
});
};
Lrz.prototype._getResize = function () {
var that = this,
img = that.img,
defaults = that.defaults,
width = defaults.width,
height = defaults.height,
orientation = that.orientation;
var ret = {
width : img.width,
height: img.height
};
if ("5678".indexOf(orientation) > -1) {
ret.width = img.height;
ret.height = img.width;
}
// 如果原图小于设定,采用原图
if (ret.width < width || ret.height < height) {
return ret;
}
var scale = ret.width / ret.height;
if (width && height) {
if (scale >= width / height) {
if (ret.width > width) {
ret.width = width;
ret.height = Math.ceil(width / scale);
}
} else {
if (ret.height > height) {
ret.height = height;
ret.width = Math.ceil(height * scale);
}
}
}
else if (width) {
if (width < ret.width) {
ret.width = width;
ret.height = Math.ceil(width / scale);
}
}
else if (height) {
if (height < ret.height) {
ret.width = Math.ceil(height * scale);
ret.height = height;
}
}
// 超过这个值base64无法生成,在IOS上
while (ret.width >= 3264 || ret.height >= 2448) {
ret.width *= 0.8;
ret.height *= 0.8;
}
return ret;
};
/**
* 获取当前js文件所在路径,必须得在代码顶部执行此函数
* @returns {string}
*/
function getJsDir (src) {
var script = null;
if (src) {
script = [].filter.call(document.scripts, function (v) {
return v.src.indexOf(src) !== -1;
})[0];
} else {
script = document.scripts[document.scripts.length - 1];
}
if (!script) return null;
return script.src.substr(0, script.src.lastIndexOf('/'));
}
/**
* 转换成formdata
* @param dataURI
* @returns {*}
*
* @source http://stackoverflow.com/questions/4998908/convert-data-uri-to-file-then-append-to-formdata
*/
function dataURItoBlob (dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new BlobFormDataShim.Blob([ia.buffer], {type: mimeString});
}
window.lrz = function (file, opts) {
return new Lrz(file, opts);
};
// 版本号来自package.json,构建时自动填充
window.lrz.version = '__packageJSON.version__';
module.exports = window.lrz;
/**
*
* ┏┓ ┏┓
* ┏┛┻━━━┛┻┓
* ┃ ┃
* ┃ ━ ┃
* ┃ ┳┛ ┗┳ ┃
* ┃ ┃
* ┃ ┻ ┃
* ┃ ┃
* ┗━┓ ┏━┛Code is far away from bug with the animal protecting
* ┃ ┃ 神兽保佑,代码无bug
* ┃ ┃
* ┃ ┗━━━┓
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛
*
*/
/***/ }),
/* 1 */
/***/ (function(module, exports) {
/*! modernizr 3.6.0 (Custom Build) | MIT *
* https://modernizr.com/download/?-exiforientation-setclasses !*/
!function(n,A,e){function o(n,A){return typeof n===A}function i(){var n,A,e,i,t,a,E;for(var r in B)if(B.hasOwnProperty(r)){if(n=[],A=B[r],A.name&&(n.push(A.name.toLowerCase()),A.options&&A.options.aliases&&A.options.aliases.length))for(e=0;e<A.options.aliases.length;e++)n.push(A.options.aliases[e].toLowerCase());for(i=o(A.fn,"function")?A.fn():A.fn,t=0;t<n.length;t++)a=n[t],E=a.split("."),1===E.length?Modernizr[E[0]]=i:(!Modernizr[E[0]]||Modernizr[E[0]]instanceof Boolean||(Modernizr[E[0]]=new Boolean(Modernizr[E[0]])),Modernizr[E[0]][E[1]]=i),s.push((i?"":"no-")+E.join("-"))}}function t(n){var A=Q.className,e=Modernizr._config.classPrefix||"";if(f&&(A=A.baseVal),Modernizr._config.enableJSClass){var o=new RegExp("(^|\\s)"+e+"no-js(\\s|$)");A=A.replace(o,"$1"+e+"js$2")}Modernizr._config.enableClasses&&(A+=" "+e+n.join(" "+e),f?Q.className.baseVal=A:Q.className=A)}function a(n,A){if("object"==typeof n)for(var e in n)r(n,e)&&a(e,n[e]);else{n=n.toLowerCase();var o=n.split("."),i=Modernizr[o[0]];if(2==o.length&&(i=i[o[1]]),"undefined"!=typeof i)return Modernizr;A="function"==typeof A?A():A,1==o.length?Modernizr[o[0]]=A:(!Modernizr[o[0]]||Modernizr[o[0]]instanceof Boolean||(Modernizr[o[0]]=new Boolean(Modernizr[o[0]])),Modernizr[o[0]][o[1]]=A),t([(A&&0!=A?"":"no-")+o.join("-")]),Modernizr._trigger(n,A)}return Modernizr}var s=[],B=[],E={_version:"3.6.0",_config:{classPrefix:"",enableClasses:!0,enableJSClass:!0,usePrefixes:!0},_q:[],on:function(n,A){var e=this;setTimeout(function(){A(e[n])},0)},addTest:function(n,A,e){B.push({name:n,fn:A,options:e})},addAsyncTest:function(n){B.push({name:null,fn:n})}},Modernizr=function(){};Modernizr.prototype=E,Modernizr=new Modernizr;var r,Q=A.documentElement,f="svg"===Q.nodeName.toLowerCase();!function(){var n={}.hasOwnProperty;r=o(n,"undefined")||o(n.call,"undefined")?function(n,A){return A in n&&o(n.constructor.prototype[A],"undefined")}:function(A,e){return n.call(A,e)}}(),E._l={},E.on=function(n,A){this._l[n]||(this._l[n]=[]),this._l[n].push(A),Modernizr.hasOwnProperty(n)&&setTimeout(function(){Modernizr._trigger(n,Modernizr[n])},0)},E._trigger=function(n,A){if(this._l[n]){var e=this._l[n];setTimeout(function(){var n,o;for(n=0;n<e.length;n++)(o=e[n])(A)},0),delete this._l[n]}},Modernizr._q.push(function(){E.addTest=a}),Modernizr.addAsyncTest(function(){var n=new Image;n.onerror=function(){a("exiforientation",!1,{aliases:["exif-orientation"]})},n.onload=function(){a("exiforientation",2!==n.width,{aliases:["exif-orientation"]})},n.src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QAiRXhpZgAASUkqAAgAAAABABIBAwABAAAABgASAAAAAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAABAAIDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD+/iiiigD/2Q=="}),i(),t(s),delete E.addTest,delete E.addAsyncTest;for(var l=0;l<Modernizr._q.length;l++)Modernizr._q[l]();n.Modernizr=Modernizr}(window,document);
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(setImmediate) {(function (root) {
// Use polyfill for setImmediate for performance gains
var asap = (typeof setImmediate === 'function' && setImmediate) ||
function (fn) {
setTimeout(fn, 1);
};
// Polyfill for Function.prototype.bind
function bind (fn, thisArg) {
return function () {
fn.apply(thisArg, arguments);
}
}
var isArray = Array.isArray || function (value) {
return Object.prototype.toString.call(value) === "[object Array]"
};
function Promise (fn) {
if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new');
if (typeof fn !== 'function') throw new TypeError('not a function');
this._state = null;
this._value = null;
this._deferreds = []
doResolve(fn, bind(resolve, this), bind(reject, this))
}
function handle (deferred) {
var me = this;
if (this._state === null) {
this._deferreds.push(deferred);
return
}
asap(function () {
var cb = me._state ? deferred.onFulfilled : deferred.onRejected
if (cb === null) {
(me._state ? deferred.resolve : deferred.reject)(me._value);
return;
}
var ret;
try {
ret = cb(me._value);
}
catch (e) {
deferred.reject(e);
return;
}
deferred.resolve(ret);
})
}
function resolve (newValue) {
try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
if (newValue === this) throw new TypeError('A promise cannot be resolved with itself.');
if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
var then = newValue.then;
if (typeof then === 'function') {
doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
return;
}
}
this._state = true;
this._value = newValue;
finale.call(this);
} catch (e) {
reject.call(this, e);
}
}
function reject (newValue) {
this._state = false;
this._value = newValue;
finale.call(this);
}
function finale () {
for (var i = 0, len = this._deferreds.length; i < len; i++) {
handle.call(this, this._deferreds[i]);
}
this._deferreds = null;
}
function Handler (onFulfilled, onRejected, resolve, reject) {
this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
this.onRejected = typeof onRejected === 'function' ? onRejected : null;
this.resolve = resolve;
this.reject = reject;
}
/**
* Take a potentially misbehaving resolver function and make sure
* onFulfilled and onRejected are only called once.
*
* Makes no guarantees about asynchrony.
*/
function doResolve (fn, onFulfilled, onRejected) {
var done = false;
try {
fn(function (value) {
if (done) return;
done = true;
onFulfilled(value);
}, function (reason) {
if (done) return;
done = true;
onRejected(reason);
})
} catch (ex) {
if (done) return;
done = true;
onRejected(ex);
}
}
Promise.prototype['catch'] = function (onRejected) {
return this.then(null, onRejected);
};
Promise.prototype.then = function (onFulfilled, onRejected) {
var me = this;
return new Promise(function (resolve, reject) {
handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
})
};
Promise.all = function () {
var args = Array.prototype.slice.call(arguments.length === 1 && isArray(arguments[0]) ? arguments[0] : arguments);
return new Promise(function (resolve, reject) {
if (args.length === 0) return resolve([]);
var remaining = args.length;
function res (i, val) {
try {
if (val && (typeof val === 'object' || typeof val === 'function')) {
var then = val.then;
if (typeof then === 'function') {
then.call(val, function (val) {
res(i, val)
}, reject);
return;
}
}
args[i] = val;
if (--remaining === 0) {
resolve(args);
}
} catch (ex) {
reject(ex);
}
}
for (var i = 0; i < args.length; i++) {
res(i, args[i]);
}
});
};
Promise.resolve = function (value) {
if (value && typeof value === 'object' && value.constructor === Promise) {
return value;
}
return new Promise(function (resolve) {
resolve(value);
});
};
Promise.reject = function (value) {
return new Promise(function (resolve, reject) {
reject(value);
});
};
Promise.race = function (values) {
return new Promise(function (resolve, reject) {
for (var i = 0, len = values.length; i < len; i++) {
values[i].then(resolve, reject);
}
});
};
/**
* Set the immediate function to execute callbacks
* @param fn {function} Function to execute
* @private
*/
Promise._setImmediateFn = function _setImmediateFn (fn) {
asap = fn;
};
Promise.prototype.always = function (callback) {
var constructor = this.constructor;
return this.then(function (value) {
return constructor.resolve(callback()).then(function () {
return value;
});
}, function (reason) {
return constructor.resolve(callback()).then(function () {
throw reason;
});
});
};
if (typeof module !== 'undefined' && module.exports) {
module.exports = Promise;
} else if (!root.Promise) {
root.Promise = Promise;
}
})(this);
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3).setImmediate))
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {var scope = (typeof global !== "undefined" && global) ||
(typeof self !== "undefined" && self) ||
window;
var apply = Function.prototype.apply;
// DOM APIs, for completeness
exports.setTimeout = function() {
return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout);
};
exports.setInterval = function() {
return new Timeout(apply.call(setInterval, scope, arguments), clearInterval);
};
exports.clearTimeout =
exports.clearInterval = function(timeout) {
if (timeout) {
timeout.close();
}
};
function Timeout(id, clearFn) {
this._id = id;
this._clearFn = clearFn;
}
Timeout.prototype.unref = Timeout.prototype.ref = function() {};
Timeout.prototype.close = function() {
this._clearFn.call(scope, this._id);
};
// Does not start the time, just sets up the members needed.
exports.enroll = function(item, msecs) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = msecs;
};
exports.unenroll = function(item) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = -1;
};
exports._unrefActive = exports.active = function(item) {
clearTimeout(item._idleTimeoutId);
var msecs = item._idleTimeout;
if (msecs >= 0) {
item._idleTimeoutId = setTimeout(function onTimeout() {
if (item._onTimeout)
item._onTimeout();
}, msecs);
}
};
// setimmediate attaches itself to the global object
__webpack_require__(4);
// On some exotic environments, it's not clear which object `setimmediate` was
// able to install onto. Search each possibility in the same order as the
// `setimmediate` library.
exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) ||
(typeof global !== "undefined" && global.setImmediate) ||
(this && this.setImmediate);
exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) ||
(typeof global !== "undefined" && global.clearImmediate) ||
(this && this.clearImmediate);
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) {
"use strict";
if (global.setImmediate) {
return;
}
var nextHandle = 1; // Spec says greater than zero
var tasksByHandle = {};
var currentlyRunningATask = false;
var doc = global.document;
var registerImmediate;
function setImmediate(callback) {
// Callback can either be a function or a string
if (typeof callback !== "function") {
callback = new Function("" + callback);
}
// Copy function arguments
var args = new Array(arguments.length - 1);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i + 1];
}
// Store and register the task
var task = { callback: callback, args: args };
tasksByHandle[nextHandle] = task;
registerImmediate(nextHandle);
return nextHandle++;
}
function clearImmediate(handle) {
delete tasksByHandle[handle];
}
function run(task) {
var callback = task.callback;
var args = task.args;
switch (args.length) {
case 0:
callback();
break;
case 1:
callback(args[0]);
break;
case 2:
callback(args[0], args[1]);
break;
case 3:
callback(args[0], args[1], args[2]);
break;
default:
callback.apply(undefined, args);
break;
}
}
function runIfPresent(handle) {
// From the spec: "Wait until any invocations of this algorithm started before this one have completed."
// So if we're currently running a task, we'll need to delay this invocation.
if (currentlyRunningATask) {
// Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
// "too much recursion" error.
setTimeout(runIfPresent, 0, handle);
} else {
var task = tasksByHandle[handle];
if (task) {
currentlyRunningATask = true;
try {
run(task);
} finally {
clearImmediate(handle);
currentlyRunningATask = false;
}
}
}
}
function installNextTickImplementation() {
registerImmediate = function(handle) {
process.nextTick(function () { runIfPresent(handle); });
};
}
function canUsePostMessage() {
// The test against `importScripts` prevents this implementation from being installed inside a web worker,
// where `global.postMessage` means something completely different and can't be used for this purpose.
if (global.postMessage && !global.importScripts) {
var postMessageIsAsynchronous = true;
var oldOnMessage = global.onmessage;
global.onmessage = function() {
postMessageIsAsynchronous = false;
};
global.postMessage("", "*");
global.onmessage = oldOnMessage;
return postMessageIsAsynchronous;
}
}
function installPostMessageImplementation() {
// Installs an event handler on `global` for the `message` event: see
// * https://developer.mozilla.org/en/DOM/window.postMessage
// * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages
var messagePrefix = "setImmediate$" + Math.random() + "$";
var onGlobalMessage = function(event) {
if (event.source === global &&
typeof event.data === "string" &&
event.data.indexOf(messagePrefix) === 0) {
runIfPresent(+event.data.slice(messagePrefix.length));
}
};
if (global.addEventListener) {
global.addEventListener("message", onGlobalMessage, false);
} else {
global.attachEvent("onmessage", onGlobalMessage);
}
registerImmediate = function(handle) {
global.postMessage(messagePrefix + handle, "*");
};
}
function installMessageChannelImplementation() {
var channel = new MessageChannel();
channel.port1.onmessage = function(event) {
var handle = event.data;
runIfPresent(handle);
};
registerImmediate = function(handle) {
channel.port2.postMessage(handle);
};
}
function installReadyStateChangeImplementation() {
var html = doc.documentElement;
registerImmediate = function(handle) {
// Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
// into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
var script = doc.createElement("script");
script.onreadystatechange = function () {
runIfPresent(handle);
script.onreadystatechange = null;
html.removeChild(script);
script = null;
};
html.appendChild(script);
};
}
function installSetTimeoutImplementation() {
registerImmediate = function(handle) {
setTimeout(runIfPresent, 0, handle);
};
}
// If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.
var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);
attachTo = attachTo && attachTo.setTimeout ? attachTo : global;
// Don't get fooled by e.g. browserify environments.
if ({}.toString.call(global.process) === "[object process]") {
// For Node.js before 0.9
installNextTickImplementation();
} else if (canUsePostMessage()) {
// For non-IE10 modern browsers
installPostMessageImplementation();
} else if (global.MessageChannel) {
// For web workers, where supported
installMessageChannelImplementation();
} else if (doc && "onreadystatechange" in doc.createElement("script")) {
// For IE 6–8
installReadyStateChangeImplementation();
} else {
// For older browsers
installSetTimeoutImplementation();
}
attachTo.setImmediate = setImmediate;
attachTo.clearImmediate = clearImmediate;
}(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self));
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(5)))
/***/ }),
/* 5 */
/***/ (function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ }),
/* 6 */
/***/ (function(module, exports) {
//@source https://xts.so/demo/compress/index.html
// 早期版本的浏览器需要用BlobBuilder来构造Blob,创建一个通用构造器来兼容早期版本
var BlobConstructor = ((function () {
try {
new Blob();
return true;
} catch (e) {
return false;
}
})()) ? window.Blob : function (parts, opts) {
var bb = new (
window.BlobBuilder
|| window.WebKitBlobBuilder
|| window.MSBlobBuilder
|| window.MozBlobBuilder
);
parts.forEach(function (p) {
bb.append(p);
});
return bb.getBlob(opts ? opts.type : undefined);
};
// Android上的AppleWebKit 534以前的内核存在一个Bug,
// 导致FormData加入一个Blob对象后,上传的文件是0字节
function hasFormDataBug () {
var bCheck = ~navigator.userAgent.indexOf('Android')
&& ~navigator.vendor.indexOf('Google')
&& !~navigator.userAgent.indexOf('Chrome');
// QQ X5浏览器也有这个BUG
return bCheck && navigator.userAgent.match(/AppleWebKit\/(\d+)/).pop() <= 534 || /MQQBrowser/g.test(navigator.userAgent);
}
var FormDataShim=(function(){
var formDataShimNums = 0;
function FormDataShim () {
var
// Store a reference to this
o = this,
// Data to be sent
parts = [],
// Boundary parameter for separating the multipart values
boundary = Array(21).join('-') + (+new Date() * (1e16 * Math.random())).toString(36),
// Store the current XHR send method so we can safely override it
oldSend = XMLHttpRequest.prototype.send;
this.getParts = function () {
return parts.toString();
};
this.append = function (name, value, filename) {
parts.push('--' + boundary + '\r\nContent-Disposition: form-data; name="' + name + '"');
if (value instanceof Blob) {
parts.push('; filename="' + (filename || 'blob') + '"\r\nContent-Type: ' + value.type + '\r\n\r\n');
parts.push(value);
}
else {
parts.push('\r\n\r\n' + value);
}
parts.push('\r\n');
};
formDataShimNums++;
XMLHttpRequest.prototype.send = function (val) {
var fr,
data,
oXHR = this;
if (val === o) {
// Append the final boundary string
parts.push('--' + boundary + '--\r\n');
// Create the blob
data = new BlobConstructor(parts);
// Set up and read the blob into an array to be sent
fr = new FileReader();
fr.onload = function () {
oldSend.call(oXHR, fr.result);
};
fr.onerror = function (err) {
throw err;
};
fr.readAsArrayBuffer(data);
// Set the multipart content type and boudary
this.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
formDataShimNums--;
if(formDataShimNums == 0){
XMLHttpRequest.prototype.send = oldSend;
}
}
else {
oldSend.call(this, val);
}
};
};
FormDataShim.prototype = Object.create(FormData.prototype);
return FormDataShim;
})();
module.exports = {
Blob : BlobConstructor,
FormData: hasFormDataBug() ? FormDataShim : FormData
};
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* exif */
(function () {
var debug = false;
var root = this;
var EXIF = function (obj) {
if (obj instanceof EXIF) return obj;
if (!(this instanceof EXIF)) return new EXIF(obj);
this.EXIFwrapped = obj;
};
if (true) {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = EXIF;
}
exports.EXIF = EXIF;
} else {
root.EXIF = EXIF;
}
var ExifTags = EXIF.Tags = {
// version tags
0x9000: "ExifVersion", // EXIF version
0xA000: "FlashpixVersion", // Flashpix format version
// colorspace tags
0xA001: "ColorSpace", // Color space information tag
// image configuration
0xA002: "PixelXDimension", // Valid width of meaningful image
0xA003: "PixelYDimension", // Valid height of meaningful image
0x9101: "ComponentsConfiguration", // Information about channels
0x9102: "CompressedBitsPerPixel", // Compressed bits per pixel
// user information
0x927C: "MakerNote", // Any desired information written by the manufacturer
0x9286: "UserComment", // Comments by user
// related file
0xA004: "RelatedSoundFile", // Name of related sound file
// date and time
0x9003: "DateTimeOriginal", // Date and time when the original image was generated
0x9004: "DateTimeDigitized", // Date and time when the image was stored digitally
0x9290: "SubsecTime", // Fractions of seconds for DateTime
0x9291: "SubsecTimeOriginal", // Fractions of seconds for DateTimeOriginal
0x9292: "SubsecTimeDigitized", // Fractions of seconds for DateTimeDigitized
// picture-taking conditions
0x829A: "ExposureTime", // Exposure time (in seconds)
0x829D: "FNumber", // F number
0x8822: "ExposureProgram", // Exposure program
0x8824: "SpectralSensitivity", // Spectral sensitivity
0x8827: "ISOSpeedRatings", // ISO speed rating
0x8828: "OECF", // Optoelectric conversion factor
0x9201: "ShutterSpeedValue", // Shutter speed
0x9202: "ApertureValue", // Lens aperture
0x9203: "BrightnessValue", // Value of brightness
0x9204: "ExposureBias", // Exposure bias
0x9205: "MaxApertureValue", // Smallest F number of lens
0x9206: "SubjectDistance", // Distance to subject in meters
0x9207: "MeteringMode", // Metering mode
0x9208: "LightSource", // Kind of light source
0x9209: "Flash", // Flash status
0x9214: "SubjectArea", // Location and area of main subject
0x920A: "FocalLength", // Focal length of the lens in mm
0xA20B: "FlashEnergy", // Strobe energy in BCPS
0xA20C: "SpatialFrequencyResponse", //
0xA20E: "FocalP