JS图片压缩
Posted 申小贺
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS图片压缩相关的知识,希望对你有一定的参考价值。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>File API Test</title> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="de.js"></script> <style> #test{ width:100px; height:100px; } </style> </head> <body> <input type="file" id="fileImg" > <form> <img src="" id="test" alt=""> </form> <script> function handleFileSelect (evt) { console.log( document.getElementById("fileImg").files); // var filebtn = document.getElementById(id); // console.log(filebtn); // var files = filebtn.target.files; // console.log(filebtn.target); // console.log(files); var files = evt.target.files; for (var i = 0, f; f = files[i]; i++) { // Only process image files. if (!f.type.match(‘image.*‘)) { continue; } var reader = new FileReader(); // Closure to capture the file information. reader.onload = (function(theFile) { return function(e) { // Render thumbnail. // console.log(evt.target.files[0]); // console.log(e.target); console.log(e.target.result); var i = document.getElementById("test"); i.src = event.target.result; console.log($(i).width()); console.log($(i).height()); $(i).css(‘width‘,$(i).width()/10+‘px‘); //$(i).css(‘height‘,$(i).height()/10+‘px‘); console.log($(i).width()); console.log($(i).height()); var quality = 50; i.src = jic.compress(i,quality).src; console.log(i.src); i.style.display = "block"; }; })(f); // Read in the image file as a data URL. reader.readAsDataURL(f); } } document.getElementById(‘fileImg‘).addEventListener(‘change‘, handleFileSelect, false); </script> </body> </html>
de.js
var jic = { /** * Receives an Image Object (can be JPG OR PNG) and returns a new Image Object compressed * @param {Image} source_img_obj The source Image Object * @param {Integer} quality The output quality of Image Object * @return {Image} result_image_obj The compressed Image Object */ compress: function(source_img_obj, quality, output_format){ var mime_type = "image/jpeg"; if(output_format!=undefined && output_format=="png"){ mime_type = "image/png"; } var cvs = document.createElement(‘canvas‘); //naturalWidth真实图片的宽度 cvs.width = source_img_obj.naturalWidth; cvs.height = source_img_obj.naturalHeight; var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0); var newImageData = cvs.toDataURL(mime_type, quality/100); var result_image_obj = new Image(); result_image_obj.src = newImageData; return result_image_obj; }, function (){} }
以上是关于JS图片压缩的主要内容,如果未能解决你的问题,请参考以下文章
在线压缩图片(TinyPNG)/ JS/CSS/HTML(YUI Compressor)
html + js 实现图片上传,压缩,预览及图片压缩后得到Blob对象继续上传问题