-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathLocalResizeIMG.js
95 lines (81 loc) · 3 KB
/
LocalResizeIMG.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/**
* 获得base64
* @param {Object} obj
* @param {Number} [obj.width] 图片需要压缩的宽度,高度会跟随调整
* @param {Number} [obj.quality=0.8] 压缩质量,不压缩为1
* @param {Function} [obj.before(this, blob, file)] 处理前函数,this指向的是input:file
* @param {Function} obj.success(obj) 处理后函数
* @example
*
*/
$.fn.localResizeIMG = function (obj) {
this.on('change', function () {
var file = this.files[0];
var URL = URL || webkitURL;
var blob = URL.createObjectURL(file);
// 执行前函数
if($.isFunction(obj.before)) { obj.before(this, blob, file) };
_create(blob, file);
this.value = ''; // 清空临时数据
});
/**
* 生成base64
* @param blob 通过file获得的二进制
*/
function _create(blob) {
var img = new Image();
img.src = blob;
img.onload = function () {
var _this = this;
//生成比例
var w = _this.width,
h = _this.width,
scale = w / h;
w = obj.width || w;
h = w / scale;
//生成canvas
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
$(canvas).attr({width : w, height : h});
ctx.drawImage(_this, 0, 0, w, h);
/**
* 生成base64
* 兼容修复移动设备需要引入mobileBUGFix.js
*/
var base64 = canvas.toDataURL('image/jpeg', obj.quality || 0.8 );
// 修复IOS
if( navigator.userAgent.match(/iphone/i) ) {
var mpImg = new MegaPixImage(img);
mpImg.render(canvas, { maxWidth: w, maxHeight: h, quality: obj.quality || 0.8, orientation: 6 });
base64 = canvas.toDataURL('image/jpeg', obj.quality || 0.8 );
}
// 修复android
if( navigator.userAgent.match(/Android/i) ) {
var encoder = new JPEGEncoder();
base64 = encoder.encode(ctx.getImageData(0,0,w,h), obj.quality * 100 || 80 );
}
// 生成结果
var result = {
blob: blob,
base64 : base64,
clearBase64: base64.substr( base64.indexOf(',') + 1 )
};
// 执行后函数
obj.success(result);
};
}
};
// 例子
/*
$('input:file').localResizeIMG({
width: 100,
quality: 0.1,
//before: function (_this, blob) {},
success: function (result) {
var img = new Image();
img.src = result.base64;
$('body').append(img);
console.log(result);
}
});
*/