forked from goker-dev/canvasResize
-
Notifications
You must be signed in to change notification settings - Fork 0
/
canvasResize.js
343 lines (327 loc) · 13 KB
/
canvasResize.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/*
*
* canvasResize
*
* Version: 1.2.0
* Date (d/m/y): 02/10/12
* Update (d/m/y): 14/05/13
* Original author: @gokercebeci
* Licensed under the MIT license
* - This plugin working with binaryajax.js and exif.js
* (It's under the MPL License http://www.nihilogic.dk/licenses/mpl-license.txt)
* Demo: http://canvasResize.gokercebeci.com/
*
* - I fixed iOS6 Safari's image file rendering issue for large size image (over mega-pixel)
* using few functions from https://github.com/stomita/ios-imagefile-megapixel
* (detectSubsampling, )
* And fixed orientation issue by using https://github.com/jseidelin/exif-js
* Thanks, Shinichi Tomita and Jacob Seidelin
*/
(function($) {
var pluginName = 'canvasResize',
methods = {
newsize: function(w, h, W, H, C) {
var c = C ? 'h' : '';
if ((W && w > W) || (H && h > H)) {
var r = w / h;
if ((r >= 1 || H === 0) && W && !C) {
w = W;
h = (W / r) >> 0;
} else if (C && r <= (W / H)) {
w = W;
h = (W / r) >> 0;
c = 'w';
} else {
w = (H * r) >> 0;
h = H;
}
}
return {
'width': w,
'height': h,
'cropped': c
};
},
dataURLtoBlob: function(data) {
var mimeString = data.split(',')[0].split(':')[1].split(';')[0];
var byteString = atob(data.split(',')[1]);
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var bb = (window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder);
if (bb) {
// console.log('BlobBuilder');
bb = new (window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder)();
bb.append(ab);
return bb.getBlob(mimeString);
} else {
// console.log('Blob');
bb = new Blob([ab], {
'type': (mimeString)
});
return bb;
}
},
/**
* Detect subsampling in loaded image.
* In iOS, larger images than 2M pixels may be subsampled in rendering.
*/
detectSubsampling: function(img) {
var iw = img.width, ih = img.height;
if (iw * ih > 1048576) { // subsampling may happen over megapixel image
var canvas = document.createElement('canvas');
canvas.width = canvas.height = 1;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, -iw + 1, 0);
// subsampled image becomes half smaller in rendering size.
// check alpha channel value to confirm image is covering edge pixel or not.
// if alpha value is 0 image is not covering, hence subsampled.
return ctx.getImageData(0, 0, 1, 1).data[3] === 0;
} else {
return false;
}
},
/**
* Update the orientation according to the specified rotation angle
*/
rotate: function(orientation, angle) {
var o = {
// nothing
1: {90: 6, 180: 3, 270: 8},
// horizontal flip
2: {90: 7, 180: 4, 270: 5},
// 180 rotate left
3: {90: 8, 180: 1, 270: 6},
// vertical flip
4: {90: 5, 180: 2, 270: 7},
// vertical flip + 90 rotate right
5: {90: 2, 180: 7, 270: 4},
// 90 rotate right
6: {90: 3, 180: 8, 270: 1},
// horizontal flip + 90 rotate right
7: {90: 4, 180: 5, 270: 2},
// 90 rotate left
8: {90: 1, 180: 6, 270: 3}
};
return o[orientation][angle] ? o[orientation][angle] : orientation;
},
/**
* Transform canvas coordination according to specified frame size and orientation
* Orientation value is from EXIF tag
*/
transformCoordinate: function(canvas, width, height, orientation) {
switch (orientation) {
case 5:
case 6:
case 7:
case 8:
canvas.width = height;
canvas.height = width;
break;
default:
canvas.width = width;
canvas.height = height;
}
var ctx = canvas.getContext('2d');
switch (orientation) {
case 1:
// nothing
break;
case 2:
// horizontal flip
ctx.translate(width, 0);
ctx.scale(-1, 1);
break;
case 3:
// 180 rotate left
ctx.translate(width, height);
ctx.rotate(Math.PI);
break;
case 4:
// vertical flip
ctx.translate(0, height);
ctx.scale(1, -1);
break;
case 5:
// vertical flip + 90 rotate right
ctx.rotate(0.5 * Math.PI);
ctx.scale(1, -1);
break;
case 6:
// 90 rotate right
ctx.rotate(0.5 * Math.PI);
ctx.translate(0, -height);
break;
case 7:
// horizontal flip + 90 rotate right
ctx.rotate(0.5 * Math.PI);
ctx.translate(width, -height);
ctx.scale(-1, 1);
break;
case 8:
// 90 rotate left
ctx.rotate(-0.5 * Math.PI);
ctx.translate(-width, 0);
break;
default:
break;
}
},
/**
* Detecting vertical squash in loaded image.
* Fixes a bug which squash image vertically while drawing into canvas for some images.
*/
detectVerticalSquash: function(img, iw, ih) {
var canvas = document.createElement('canvas');
canvas.width = 1;
canvas.height = ih;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
var data = ctx.getImageData(0, 0, 1, ih).data;
// search image edge pixel position in case it is squashed vertically.
var sy = 0;
var ey = ih;
var py = ih;
while (py > sy) {
var alpha = data[(py - 1) * 4 + 3];
if (alpha === 0) {
ey = py;
} else {
sy = py;
}
py = (ey + sy) >> 1;
}
var ratio = py / ih;
return ratio === 0 ? 1 : ratio;
},
callback: function(d) {
return d;
},
extend: function() {
var target = arguments[0] || {}, a = 1, al = arguments.length, deep = false;
if (target.constructor === Boolean) {
deep = target;
target = arguments[1] || {};
}
if (al === 1) {
target = this;
a = 0;
}
var prop;
for (; a < al; a++)
if ((prop = arguments[a]) !== null)
for (var i in prop) {
if (target === prop[i])
continue;
if (deep && typeof prop[i] === 'object' && target[i])
methods.extend(target[i], prop[i]);
else if (prop[i] !== undefined)
target[i] = prop[i];
}
return target;
}
},
defaults = {
width: 300,
height: 0,
crop: false,
quality: 80,
rotate: 0,
'callback': methods.callback
};
function Plugin(file, options) {
this.file = file;
// EXTEND
this.options = methods.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function() {
//this.options.init(this);
var $this = this;
var file = this.file;
var reader = new FileReader();
reader.onloadend = function(e) {
var dataURL = e.target.result;
var byteString = atob(dataURL.split(',')[1]);
var binary = new BinaryFile(byteString, 0, byteString.length);
var exif = EXIF.readFromBinaryFile(binary);
var img = new Image();
img.onload = function(e) {
var orientation = exif['Orientation'] || 1;
orientation = methods.rotate(orientation, $this.options.rotate);
// CW or CCW ? replace width and height
var size = (orientation >= 5 && orientation <= 8)
? methods.newsize(img.height, img.width, $this.options.width, $this.options.height, $this.options.crop)
: methods.newsize(img.width, img.height, $this.options.width, $this.options.height, $this.options.crop);
var iw = img.width, ih = img.height;
var width = size.width, height = size.height;
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
ctx.save();
methods.transformCoordinate(canvas, width, height, orientation);
// over image size
if (methods.detectSubsampling(img)) {
iw /= 2;
ih /= 2;
}
var d = 1024; // size of tiling canvas
var tmpCanvas = document.createElement('canvas');
tmpCanvas.width = tmpCanvas.height = d;
var tmpCtx = tmpCanvas.getContext('2d');
var vertSquashRatio = methods.detectVerticalSquash(img, iw, ih);
var sy = 0;
while (sy < ih) {
var sh = sy + d > ih ? ih - sy : d;
var sx = 0;
while (sx < iw) {
var sw = sx + d > iw ? iw - sx : d;
tmpCtx.clearRect(0, 0, d, d);
tmpCtx.drawImage(img, -sx, -sy);
var dx = Math.floor(sx * width / iw);
var dw = Math.ceil(sw * width / iw);
var dy = Math.floor(sy * height / ih / vertSquashRatio);
var dh = Math.ceil(sh * height / ih / vertSquashRatio);
ctx.drawImage(tmpCanvas, 0, 0, sw, sh, dx, dy, dw, dh);
sx += d;
}
sy += d;
}
ctx.restore();
tmpCanvas = tmpCtx = null;
// if rotated width and height data replacing issue
var newcanvas = document.createElement('canvas');
newcanvas.width = size.cropped === 'h' ? height : width;
newcanvas.height = size.cropped === 'w' ? width : height;
var x = size.cropped === 'h' ? (height - width) * .5 : 0;
var y = size.cropped === 'w' ? (width - height) * .5 : 0;
newctx = newcanvas.getContext('2d');
newctx.drawImage(canvas, x, y, width, height);
console.log(file, file.type);
if (file.type === "image/png") {
var data = newcanvas.toDataURL(file.type);
} else {
var data = newcanvas.toDataURL("image/jpeg", ($this.options.quality * .01));
}
// CALLBACK
$this.options.callback(data, newcanvas.width, newcanvas.height);
// });
};
img.src = dataURL;
// =====================================================
};
reader.readAsDataURL(file);
//reader.readAsBinaryString(file);
}
};
$[pluginName] = function(file, options) {
if (typeof file === 'string')
return methods[file](options);
else
new Plugin(file, options);
};
})(window);