<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<input type="file" onchange="getImg(this)"/>
<img src="" id="img" >
<script>
function getImg(e){
let [file] = e.files
let render = new FileReader()
render.readAsDataURL(file)
render.onload = res => {
// console.log(res.target.result)
let {result} = res.target
img.src = result// 讲 base64 文件流付给img
img.onload = res => {
let re = new Blob([result], {type:'image/jpeg'})
console.log(re.size/1024)
if(re.size > (1024 * 1024)) {
result = compression(img)
img.src = result
}
}
render = null // 清空
}
render.onerror = err => {
console.log('上传失败', err)
}
}
// 图片压缩
function compression(image) {
let canvas = document.createElement('canvas')
canvas.width = img.naturalWidth
canvas.height = img.naturalHeight
canvas.setAttribute('id', 'ctx')
let ctx = canvas.getContext("2d");
let multiple = (1024 * 1024) / (img.naturalWidth * img.naturalHeight) // 压缩倍率,保证压缩在小于1MB
multiple = multiple > 0.8 ? 0.8 : multiple
ctx.drawImage(image, 0, 0, img.naturalWidth, img.naturalHeight)
return canvas.toDataURL('image/jpeg', multiple) // 压缩后的图片的文件流
}
</script>
</body>
</html>