/
ImageUploader.vue
534 lines (472 loc) · 16.8 KB
/
ImageUploader.vue
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
<template>
<div>
<img v-show="imagePreview" :src="imagePreview" class="img-preview" width="100">
<input
:id="id"
:class="className"
type="file"
@change="uploadFile"
accept="image/*"
:capture="capture"
>
<slot name="upload-label"></slot>
</div>
</template>
<script>
/**
* vue-ImageUploader: a to-the-point vue-component for client-side image upload with resizing of images (JPG, PNG, GIF)
*
* Code based on ImageUploader (c) Ross Turner (https://github.com/rossturner/HTML5-ImageUploader).
* Adapted for Vue by Svale Fossåskaret / Kartoteket with some modifications.
*
* Requires exif.js 2.3.0 (https://github.com/exif-js/exif-js) for JPEG autoRotate functions.
*
*
* TODO Items:
* 1. Progress Report
* 2. Multiple Files
* 3. Support custom completion callback
* 4. Propper unit testing with https://github.com/visionmedia/supertest
* 5. Clean up scaffolding and project files
*
* LICENSE (from original ImageUploader files by Ross Turner):
*
* Copyright (c) 2012 Ross Turner and contributors (https://github.com/zsinj)
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
**/
/* Dependecies */
/* global EXIF:true, dataURLtoBlob:true */
import EXIF from 'exif-js'
import dataURLtoBlob from 'blueimp-canvas-to-blob'
export default {
name: 'image-uploader',
props: {
/**
* The ID for the file input, required if more than one instance should be used on the same page.
*
* @default fileInput
* @type {String}
*/
id: {
type: String,
default: 'fileInput'
},
/**
* An integer in pixels for the maximum width allowed for uploaded images, selected images with a greater width than this value will be scaled down before upload.
* @default 1024
* @type {Number}
*/
maxWidth: {
type: Number,
default: 1024
},
/**
* An integer in pixels for the maximum height allowed for uploaded images, selected images with a greater height than this value will be scaled down before upload.
* @default 1024
* @type {Number}
*/
maxHeight: {
type: Number,
default: 1024
},
/**
* TODO: Does not make sens to me
* A float value in megapixels (MP) for the maximum overall size of the image allowed for uploaded images, selected images with a greater size than this value will be scaled down before upload. If the value is null or is not specified, then maximum size restriction is not applied
* @default null
* @type {Number}
*/
maxSize: {
type: Number,
default: null
},
/**
* A float between 0 and 1.00 for the image quality to use in the resulting image data, around 0.9 is recommended.
* @default 1.00
* @type {Number}
*/
quality: {
type: Number,
default: 1.00
},
/**
* Allows scaling down to a specified fraction of the original size. (Example: a value of 0.5 will reduce the size by half.) Accepts a decimal value between 0 and 1.
* @default null
* @type {Number}
*/
scaleRatio: {
type: Number,
default: null
},
/**
* A boolean flag, if true then EXIF information from the image is parsed and the image is rotated correctly before upload. If false, then no processing is performed, and unwanted image flipping can happen.
* @default false
* @type {Boolean}
*/
autoRotate: {
type: Boolean,
default: false
},
/**
* A boolean flag to toogle an img-tag displaying the uploaded image. When set to false no img-tag is displayed
* @default true
* @type {Boolean}
*/
preview: {
type: Boolean,
default: true
},
/**
* Sets the desired format for the returned image. Available formats are
* 'string' (base64), verbose (object) or 'blob' (object)
* @default {base64}
* @type {String}
*/
outputFormat: {
type: String,
default: 'string'
},
/**
* Sets the desired class name for the input element
* @default {fileinput}
* @type {String or Array}
*/
className: {
type: [String, Array],
default: 'fileinput'
},
/**
* Sets an optional capture attribute. (camera, user, environment)
* @default empty
* @type {String}
*/
capture: {
type: [String],
default: null
},
/**
* How much to write to the console. 0 = silent. 1 = quite. 2 = loud
* @default false
* @type {Boolean}
*/
debug: {
type: Number,
default: 0
}
},
data () {
return {
imagePreview: null
}
},
methods: {
/**
* Get file from input
* @param {object} event
*/
uploadFile (e) {
var file = e.target.files && e.target.files.length ? e.target.files[0] : null
if (file) {
this.emitLoad()
this.handleFile(file, this.emitComplete)
}
},
/**
* Emit event with output
* @param {mixed} output the resized image. type can be simple dataUrl string, verbose object or Blob instance
* @return {[type]} [description]
*/
emitEvent (output) {
if (this.debug > 1) {
console.log('emitEvent() is called with output:')
console.log(output)
}
this.$emit('input', output)
this.$emit('change', output)
},
emitLoad () {
this.$emit('onUpload')
},
emitComplete () {
this.$emit('onComplete')
},
/**
* Handels the file manipulation on upload
* @param {File} file The current original uploaded file
* @param {function} completionCallback Not implemted yet
* @return {} nada
*/
handleFile (file, completionCallback) {
if (this.debug > 1) {
console.log('handleFile() is called with file:')
console.log(file)
}
this.currentFile = file
var that = this
var img = document.createElement('img')
var reader = new window.FileReader()
reader.onload = function (e) {
if (that.debug > 1) {
console.log('reader.onload() is triggered')
}
img.src = e.target.result
img.onload = function () {
if (that.debug > 1) {
console.log('img.onload() is triggered')
}
// Rotate image first if required
if (that.autoRotate) {
if (typeof EXIF === 'undefined') {
console.warn('Missing EXIF library! exif-js.js must be loaded to use autoRotate')
console.warn('Continuing without rotation')
that.scaleImage(img, completionCallback)
} else {
if (that.debug) {
console.log('ImageUploader: detecting image orientation...')
}
if ((typeof EXIF.getData === 'function') && (typeof EXIF.getTag === 'function')) {
EXIF.getData(img, function () {
var orientation = EXIF.getTag(this, 'Orientation')
if (that.debug) {
console.log('ImageUploader: image orientation from EXIF tag = ' + orientation)
}
that.scaleImage(img, completionCallback, orientation)
})
} else {
console.error('ImageUploader: can\'t read EXIF data, the Exif.js library not found')
that.scaleImage(img, completionCallback)
}
}
} else {
if (that.debug) {
console.log('No autoRotate')
}
that.scaleImage(img, completionCallback)
}
}
}
reader.readAsDataURL(file)
},
/**
* Performance orientation and scaling logic
* @param {[type]} img [description]
* @param {[type]} completionCallback [description]
* @param {[type]} orientation [description]
* @return {[type]} [description]
*/
scaleImage (img, completionCallback, orientation) {
if (this.debug > 1) {
console.log('scaleImage() is called')
}
var canvas = document.createElement('canvas')
canvas.width = img.width
canvas.height = img.height
var ctx = canvas.getContext('2d')
ctx.save()
// Good explanation of EXIF orientation is here http://www.daveperrett.com/articles/2012/07/28/exif-orientation-handling-is-a-ghetto/
var width = canvas.width
var styleWidth = canvas.style.width
var height = canvas.height
var styleHeight = canvas.style.height
if (typeof orientation === 'undefined') {
orientation = 1
}
if (orientation) {
if (orientation > 4) {
canvas.width = height
canvas.style.width = styleHeight
canvas.height = width
canvas.style.height = styleWidth
}
switch (orientation) {
case 2:
ctx.translate(width, 0)
ctx.scale(-1, 1)
break
case 3:
ctx.translate(width, height)
ctx.rotate(Math.PI)
break
case 4:
ctx.translate(0, height)
ctx.scale(1, -1)
break
case 5:
ctx.rotate(0.5 * Math.PI)
ctx.scale(1, -1)
break
case 6:
ctx.rotate(0.5 * Math.PI)
ctx.translate(0, -height)
break
case 7:
ctx.rotate(0.5 * Math.PI)
ctx.translate(width, -height)
ctx.scale(-1, 1)
break
case 8:
ctx.rotate(-0.5 * Math.PI)
ctx.translate(-width, 0)
break
}
}
ctx.drawImage(img, 0, 0)
ctx.restore()
// Let's find the max available width for scaled image
var ratio = canvas.width / canvas.height
var mWidth = Math.min(this.maxWidth, ratio * this.maxHeight)
// suggested re-write by https://github.com/ryancramerdesign
// https://github.com/rossturner/HTML5-ImageUploader/issues/13
if (this.maxSize > 0 && (this.maxSize < (canvas.width * canvas.height) / 1000000)) {
var mSize = Math.floor(Math.sqrt(this.maxSize * ratio) * 1000)
mWidth = mWidth > 0 ? Math.min(mWidth, mSize) : mSize
}
if (this.scaleRatio) {
mWidth = Math.min(mWidth, Math.floor(this.scaleRatio * canvas.width))
}
if (this.debug) {
console.log('ImageUploader: original image size = ' + canvas.width + ' X ' + canvas.height)
console.log('ImageUploader: scaled image size = ' + mWidth + ' X ' + Math.floor(mWidth / ratio))
}
if (mWidth <= 0) {
mWidth = 1
console.warning('ImageUploader: image size is too small')
}
while (canvas.width >= (2 * mWidth)) {
canvas = this.getHalfScaleCanvas(canvas)
}
if (canvas.width > mWidth) {
canvas = this.scaleCanvasWithAlgorithm(canvas, mWidth)
}
// suggested re-write by https://github.com/ryancramerdesign
// https://github.com/rossturner/HTML5-ImageUploader/issues/13
var quality = this.currentFile.type === 'image/jpeg' ? this.quality : 1.0
var imageData = canvas.toDataURL(this.currentFile.type, quality)
if (typeof this.onScale === 'function') {
this.onScale(imageData)
}
if (this.debug > 1) {
console.log('New ImageData is ready. Set Preview, emitEvent and trigger optional callback ')
}
// Display preview of the new image
if (this.preview) {
this.imagePreview = imageData
}
// Return the new image
// this.emitEvent(this.currentFile) // DEBUG
this.emitEvent(this.formatOutput(imageData))
// complete
completionCallback()
// this.performUpload(imageData, completionCallback)
},
scaleCanvasWithAlgorithm (canvas, maxWidth) {
var scaledCanvas = document.createElement('canvas')
var scale = maxWidth / canvas.width
scaledCanvas.width = canvas.width * scale
scaledCanvas.height = canvas.height * scale
var srcImgData = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height)
var destImgData = scaledCanvas.getContext('2d').createImageData(scaledCanvas.width, scaledCanvas.height)
this.applyBilinearInterpolation(srcImgData, destImgData, scale)
scaledCanvas.getContext('2d').putImageData(destImgData, 0, 0)
return scaledCanvas
},
/* eslint-disable camelcase */
applyBilinearInterpolation (srcCanvasData, destCanvasData, scale) {
function inner (f00, f10, f01, f11, x, y) {
var un_x = 1.0 - x
var un_y = 1.0 - y
return (f00 * un_x * un_y + f10 * x * un_y + f01 * un_x * y + f11 * x * y)
}
var i, j
var iyv, iy0, iy1, ixv, ix0, ix1
var idxD, idxS00, idxS10, idxS01, idxS11
var dx, dy
var r, g, b, a
for (i = 0; i < destCanvasData.height; ++i) {
iyv = i / scale
iy0 = Math.floor(iyv)
// Math.ceil can go over bounds
iy1 = (Math.ceil(iyv) > (srcCanvasData.height - 1) ? (srcCanvasData.height - 1) : Math.ceil(iyv))
for (j = 0; j < destCanvasData.width; ++j) {
ixv = j / scale
ix0 = Math.floor(ixv)
// Math.ceil can go over bounds
ix1 = (Math.ceil(ixv) > (srcCanvasData.width - 1) ? (srcCanvasData.width - 1) : Math.ceil(ixv))
idxD = (j + destCanvasData.width * i) * 4
// matrix to vector indices
idxS00 = (ix0 + srcCanvasData.width * iy0) * 4
idxS10 = (ix1 + srcCanvasData.width * iy0) * 4
idxS01 = (ix0 + srcCanvasData.width * iy1) * 4
idxS11 = (ix1 + srcCanvasData.width * iy1) * 4
// overall coordinates to unit square
dx = ixv - ix0
dy = iyv - iy0
// I let the r, g, b, a on purpose for debugging
r = inner(srcCanvasData.data[idxS00], srcCanvasData.data[idxS10], srcCanvasData.data[idxS01], srcCanvasData.data[idxS11], dx, dy)
destCanvasData.data[idxD] = r
g = inner(srcCanvasData.data[idxS00 + 1], srcCanvasData.data[idxS10 + 1], srcCanvasData.data[idxS01 + 1], srcCanvasData.data[idxS11 + 1], dx, dy)
destCanvasData.data[idxD + 1] = g
b = inner(srcCanvasData.data[idxS00 + 2], srcCanvasData.data[idxS10 + 2], srcCanvasData.data[idxS01 + 2], srcCanvasData.data[idxS11 + 2], dx, dy)
destCanvasData.data[idxD + 2] = b
a = inner(srcCanvasData.data[idxS00 + 3], srcCanvasData.data[idxS10 + 3], srcCanvasData.data[idxS01 + 3], srcCanvasData.data[idxS11 + 3], dx, dy)
destCanvasData.data[idxD + 3] = a
}
}
},
getHalfScaleCanvas (canvas) {
var halfCanvas = document.createElement('canvas')
halfCanvas.width = canvas.width / 2
halfCanvas.height = canvas.height / 2
halfCanvas.getContext('2d').drawImage(canvas, 0, 0, halfCanvas.width, halfCanvas.height)
return halfCanvas
},
/**
* Sets the format of the component output
* @param {string} imageData dataUrl
* @return {mixed} Either simple dataUrl string or
* object with dataURl and metadata or
* blob
*/
formatOutput (imageData) {
if (this.debug) {
console.log('ImageUploader: outputFormat: ' + this.outputFormat)
}
if (this.outputFormat === 'blob') {
if (typeof dataURLtoBlob === 'undefined') {
console.warn('Missing library! blueimp-canvas-to-blob.js must be loaded to output as "blob"')
console.warn('Falling back to default base64 dataUrl')
return imageData
}
return dataURLtoBlob(imageData)
}
if (this.outputFormat === 'verbose') {
return {
dataUrl: imageData,
name: this.currentFile.name,
lastModified: this.currentFile.lastModified,
lastModifiedDate: this.currentFile.lastModifiedDate
}
}
// simple base64 dataUrl string by default
return imageData
}
},
created () {
if (this.debug) {
console.log('Initialised ImageUploader')
}
}
}
</script>