-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
69 lines (66 loc) · 1.97 KB
/
Copy pathindex.js
File metadata and controls
69 lines (66 loc) · 1.97 KB
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
/* eslint-env browser */
module.exports = function (config) {
function readAsDataURL (file) {
if (!(file instanceof Blob)) {
throw new TypeError('Must be a File or Blob')
}
return new Promise(function (resolve, reject) {
var reader = new FileReader()
reader.onload = function (e) {
resolve(e.target.result)
}
reader.onerror = function (e) {
reject(`Error reading ${file.name}: ${e.target.result}`)
}
reader.readAsDataURL(file)
})
}
function makeImage (fileReaderResult) {
return new Promise(function (resolve, reject) {
var img = new Image()
img.onload = function () {
resolve(img)
}
img.onerror = function (e) {
reject('Error resizing image: ', e)
}
img.src = fileReaderResult
})
}
function compressImage (img) {
// Get image dimensions and calculate appropriate ratio to use
var w = img.width
var h = img.height
var ratioWidth = w > config.maxWidth ? config.maxWidth / w : 1
var ratioHeight = h > config.maxHeight ? config.maxHeight / h : 1
var ratio = Math.min(ratioWidth, ratioHeight)
// Calculate new dimensions
var newWidth = Math.floor(w * ratio)
var newHeight = Math.floor(h * ratio)
// Draw canvas using new dimensions
var canvas = document.createElement('canvas')
canvas.width = newWidth
canvas.height = newHeight
var ctx = canvas.getContext('2d', {
preserveDrawingBuffer: true
})
ctx.drawImage(img, 0, 0, newWidth, newHeight)
// Turn canvas into file data
var dataURL = canvas.toDataURL('image/jpeg', 0.5)
var a = dataURL.split(',')[1]
var blob = atob(a)
var array = []
for (var k = 0; k < blob.length; k++) {
array.push(blob.charCodeAt(k))
}
var data = new Blob([new Uint8Array(array)], {
type: 'image/jpeg'
})
return data
}
return function (file) {
return readAsDataURL(file)
.then(makeImage)
.then(compressImage)
}
}