H5图片压缩、上传

【前言】

这里着重说多图压缩成base64上传

html

1
<input type="file" accept="image/*" multiple="multiple" onChange={uploadImage()}/>

多图转换base64

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
uploadImage(event){
const img_base = [];
const files_array = [];
const files = event.target.files;
const files_length = files.length;

for (let n = 0; n < files_length; n++) {
files_array.push(files[n])
}

const PromiseForEach = (files) => {
return Promise.all(files.map(obj => {
return new Promise((resolve) => {
const reader = new FileReader();
reader.readAsDataURL(obj);
reader.onloadend = (e) => {
let base64 = e.target.result;
imgZipBase64(base64,400,(base)=>{
img_url = img_url.concat(base);
resolve();
});
};
});
})).then(() => {
img_url.map((o) => {
o = o.indexOf(',') === -1 ? o : o.split(',')[1];
img_base.push(o);
});
}).then(() => {
console.log('得到所有base64',img_url);
console.log('过滤前缀的base64',img_base);
});
};
PromiseForEach(files_array);
//每次选择后清空file值,确保可以选择相同图片
event.target.value = '';
}
压缩图片
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
/**
* 压缩图片
* @param src 图片链接或原图base64
* @param size 定义最大长宽
* @param callback 返回压缩后base64
*/
const imgZipBase64 = (src, size, callback) =>{
let img = new Image();
let base = null;
img.src = src;
// 缩放图片需要的canvas
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
img.onload = () => {
// 图片原始尺寸
console.log(img.width,img.height);
let originWidth = img.width;
let originHeight = img.height;
// 最大尺寸限制
let maxWidth = size||400, maxHeight = size||400;
// 目标尺寸
let targetWidth = originWidth, targetHeight = originHeight;
// 图片尺寸超过400x400的限制
if (originWidth > maxWidth || originHeight > maxHeight) {
if (originWidth / originHeight > maxWidth / maxHeight) {
// 更宽,按照宽度限定尺寸
targetWidth = maxWidth;
targetHeight = Math.round(maxWidth * (originHeight / originWidth));
} else {
targetHeight = maxHeight;
targetWidth = Math.round(maxHeight * (originWidth / originHeight));
}
}

// canvas对图片进行缩放
canvas.width = targetWidth;
canvas.height = targetHeight;
// 清除画布
context.clearRect(0, 0, targetWidth, targetHeight);
// 图片压缩
context.drawImage(img, 0, 0, targetWidth, targetHeight);
console.log(canvas.width,canvas.height);
// canvas转为base64
base = canvas.toDataURL('image/png');
callback(base);
};
};

注意:ios手机上传照片时如果压缩处理,会造成orientation丢失,图片方向错乱,推荐使用’exif-orientation’获取方向;

相关文献