图片上传以及压缩

本文主要介绍图片上传以及压缩。

上传图片按钮

1
<input type="file" name="img" id="imgUpload" accept="image/jpeg, image/png, image/jpg, image/gif" onchange="uploadImg(this)">

图片上传

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function uploadImg(imgUrl) {
//判断是否支持FileReader
if (window.FileReader) {
var reader = new FileReader();
} else {
alert("您的设备不支持图片预览功能,如需该功能请升级您的设备!");
}

//获取文件
var file = imgUrl.files[0];
var picType = file.name.substring(file.name.lastIndexOf(".") + 1, file.name.length); //获取图片的后缀名
var imageType = /^image\//;
//是否是图片
if (!imageType.test(file.type)) {
alert("请选择图片!");
return;
}
//读取完成
reader.onload = function (e) {
console.log(e.target.result)
};
reader.readAsDataURL(file);
}

图片压缩

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
var canvas = document.createElement("canvas");
var ctx = canvas.getContext('2d');
var tCanvas = document.createElement("canvas");
var tctx = tCanvas.getContext("2d");
var maxsize = 100 * 1024;

// 参数 img 为 <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAE..."> 这种格式
function compress(img) {
var initSize = img.src.length;
var width = img.width;
var height = img.height;
// 如果图片大于四百万像素,计算压缩比并将大小压至400万以下
var ratio;
if ((ratio = width * height / 4000000) > 1) {
ratio = Math.sqrt(ratio);
width /= ratio;
height /= ratio;
} else {
ratio = 1;
}
canvas.width = width;
canvas.height = height;
// 铺底色
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 如果图片像素大于100万则使用瓦片绘制
var count;
if ((count = width * height / 1000000) > 1) {
count = ~~(Math.sqrt(count) + 1); // 计算要分成多少块瓦片
// 计算每块瓦片的宽和高
var nw = ~~(width / count);
var nh = ~~(height / count);
tCanvas.width = nw;
tCanvas.height = nh;
for (var i = 0; i < count; i++) {
for (var j = 0; j < count; j++) {
tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
}
}
} else {
ctx.drawImage(img, 0, 0, width, height);
}
// 进行最小压缩
var ndata = canvas.toDataURL('image/jpeg', 0.1);
tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
return ndata; // 返回压缩后的数据 格式: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAE...
}