@Wangww0925
2019-08-07T07:56:45.000000Z
字数 1223
阅读 168
js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="file">
</body>
</html>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script>
// input上传图片
$("input").change(function(e){
var that = this
if(that.value){
if(!/.(gif|jpg|jpeg|png|GIF|JPG|png)$/.test(that.value)){
alert("图片类型必须是.gif,jpeg,jpg,png中的一种");
$(that).val("");
return false
}
var reader = new FileReader();
reader.onload = (function (file) {
return function (e) {
var url = this.result;
// 超出1.5Mb大小需压缩
if (url.length > 1572864) {
var img = new Image();
img.src = url;
img.onload = function () {
//生成比例
var width = img.width, height = img.height;
//计算缩放比例
var rate = 1;
var maxLen = 1000;
if (width >= height) {
if (width > maxLen) {
rate = maxLen / width;
}
} else {
if (height > maxLen) {
rate = maxLen / height;
}
};
img.width = width * rate;
img.height = height * rate;
//生成canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
var base64 = canvas.toDataURL('image/jpeg', 0.9);
console.log("超出1.5Mb大小需压缩", base64); // 这个就是base64的数据了
};
} else {
console.log(this.result); // 这个就是base64的数据了
}
}
})(e.target.files[0]);
reader.readAsDataURL(e.target.files[0]);
}
})
</script>
作者 wendy
2019 年 7月 30日