JS_图片压缩并预览
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>上传图片并预览</title> </head> <body> 点击下方图片选择要上传的图片<br> <label> <input id="upload" type="file" style="position:absolute;opacity:0" accept="image/*" onchange="show('upload','img')"> <img id="img" src="../static/images/upload.jpg" width="30%" height="30%" alt="图片加载失败"> </label> <script> function show(fileId, imgId) { var file = document.getElementById(fileId).files[0]; var imgShow = document.getElementById(imgId); var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function () { var imgSrc = this.result; if (file.size > 1 * 1024 * 1024) { var img=new Image(); img.src=this.result; img.onload=function(){ imgSrc= compress(img,0.3,file.type); imgShow.src = imgSrc; } }else{ imgShow.src = imgSrc; } } } function compress(img, quality, type) { var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); canvas.width = img.width/2; canvas.height = img.height/2; context.drawImage(img, 0, 0, canvas.width, canvas.height); var res = canvas.toDataURL(type, quality); return res; } </script> </body> </html>
害怕失败的人,已经是一个loser!