1 ///用于上传的图片 2 <input type="file" name="imageFile" id="imageFile" /> 3 //压缩按钮 4 <input type="button" onclick="change()" value="压缩图"/>
javaScripts处理:
window.change = function () { var oFile = document.getElementById('imageFile').files[0]; //读取文件 var reader = new FileReader(), img = new Image(); ///加载地址 reader.readAsDataURL(oFile); reader.onload = function () { //文件加载完成 var url = reader.result; img.src = url; }; img.onload = function () { init(); } function init() { var w = img.width, h = img.height; var canvas = document.createElement("canvas"); var ctx = canvas.getContext('2d'); //压缩比例为3 canvas.width = w / 3; canvas.height = h / 3; //将图片转化为canvas;并显示出来 ctx.drawImage(img, 0, 0, w, h, 0, 0, canvas.width, canvas.height); var quality = 0.3; //图片的质量,这里设置的是0.3 var data = canvas.toDataURL("image/png"); //获取画布图片,并且要png格式 //下载图片的两个方法 //window.location.href = data; //saveFile(data, new Date().getTime() + ".png"); document.body.appendChild(canvas); } //下载图片 function saveFile(data, filename) { var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a'); save_link.href = data; save_link.download = filename; var event = document.createEvent('MouseEvents'); event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); save_link.dispatchEvent(event); }; }