-
Notifications
You must be signed in to change notification settings - Fork 0
/
src.js
67 lines (64 loc) · 2.1 KB
/
src.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
/**
* Created by b5156 on 2017/8/18.
*/
export default function imgfile2base64(file, complete, opt) {
var defaultOpt = {
width: null,
height: null,
quality: 1,
fileTypes: ["image/gif", "image/png", "image/jpeg", "image/bmp", "image/webp"],
targetFileType: 'image/jpeg'
};
if (!opt) {
opt = defaultOpt;
} else {
for (var k in defaultOpt) {
if (!opt[k]) {
opt[k] = defaultOpt[k];
}
}
}
if (file instanceof File === false) {
throw new Error('not a File');
}
if (opt.fileTypes.indexOf(file.type) < 0) {
throw new Error('unsupported image type');
}
if (!FileReader) {
throw new Error('unsupported FileReader');
}
if (typeof complete !== 'function') {
throw new Error('complete should be a function');
}
if (typeof opt.quality !== 'number' || opt.quality > 1 || opt.quality < 0) {
throw new Error('quality should be between 0 and 1');
}
if (opt.width && typeof opt.width !== 'number') {
throw new Error('width should be a number');
}
if (opt.height && typeof opt.height !== 'number') {
throw new Error('height should be a number');
}
var reader = new FileReader();
reader.onload = function (e) {
var img = new Image();
img.src = e.target.result;
img.onload = function () {
var scale = img.width / img.height;
var w = opt.width || img.width;
var h = opt.height || (w / scale);
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var anw = document.createAttribute("width");
anw.nodeValue = w;
var anh = document.createAttribute("height");
anh.nodeValue = h;
canvas.setAttributeNode(anw);
canvas.setAttributeNode(anh);
ctx.drawImage(img, 0, 0, w, h);
var base64 = canvas.toDataURL(opt.targetFileType, opt.quality);
complete(base64);
}
};
reader.readAsDataURL(file);
}