演示
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>压缩图片</title>
</head>
<body>
<input id='file' type="file">
<script>var eleFile = document.querySelector('#file')var file;var render = new FileReader(), img = new Image();render.onload = function(e) {img.src = e.target.result}// 获取图片文件eleFile.addEventListener('change', function(e) {file = e.target.files[0];if(file.type.indexOf('image') === 0) {//读取文件,并返回一个URL格式的Base64字符串render.readAsDataURL(file)}})//使用canvas把图片画出来var canvas = document.createElement('canvas');var context = canvas.getContext('2d');img.onload = function() {//原始尺寸var originWidth = this.width;var originHeight = this.height;//最大尺寸限制var maxWidth = 200, maxHeight = 200// 目标尺寸var targetWidth = originWidth, targetHeight = originHeight;//当原始尺寸大于200*200时候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.width = targetWidth;canvas.height = targetHeight;//清除画布context.clearRect(0,0,targetWidth, targetHeight)//图片压缩context.drawImage(img, 0, 0, targetWidth, targetHeight);//canvas 转为blob并上传canvas.toBlob(function(blob) {try {var xhr = new XMLHttpRequest();xhr.onreadystatechange = function() {{if(xhr.status == 200) {}}}//开始上传xhr.open('POST','upload.php', true);xhr.send(blob)} catch (error) {console.log(error)}}, file.type || 'image/png')//在页面预览原图片var div1 = document.createElement('div')div1.innerText = '原图:'document.body.appendChild(div1)document.body.appendChild(img)//canvas预览var div2 = document.createElement('div')div2.innerText = 'canvas图:'document.body.appendChild(div2)document.body.appendChild(canvas)}</script>
</body>
</html>
分析:原理是用canvas的生成的图片,控制其大小来进行图片的压缩,需要注意的是,如果图片的尺寸太小,会导致图片模糊,使用时候,注意设置其比例控制。
1、通过FileReader读取图片文件,用 Image来装图片url(可以用来预览)
2、转化成base64字符串模式
3、通过maxWidth,MaxHeight和比例来控制最终的canvas的宽高 4、用canvas画图
5、在把canvas输出blob文件,进行上传