<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>javascript使用canvas压缩图像</title> <script type="text/javascript"> var jic = {//javascript使用HTML5 canvas压缩图像源代码,压缩js代码来源:,做了些许更改 /** * Receives an Image Object (can be JPG OR PNG) and returns a new Image Object compressed 使用canvas压缩图片,返回图片压缩后的base64字符串内容 * @param {Image} source_img_obj The source Image Object 被压缩的图片对象,注意图片对象一定要加载当前压缩的图片base64内容,要不会报错 * @param {Integer} quality The output quality of Image Object 压缩比,越小压缩越多 * @return {string} compressData The compressed Image base64 string 图像压缩后的base64编码字符串 */ compress: function (source_img_obj, quality, output_format) { var mime_type = "image/jpeg"; if (output_format == "png") mime_type = "image/png"; var canvas = document.createElement('canvas'); //naturalWidth真实图片的宽度 canvas.width = source_img_obj.naturalWidth; canvas.height = source_img_obj.naturalHeight; var ctx = canvas.getContext("2d").drawImage(source_img_obj, 0, 0); var compressData = canvas.toDataURL(mime_type, quality / 100); return compressData; } } </script> </head> <body><input type="file" onchange="compressImage(this.files[0])"/> <div id="dvRst"></div> <img id="imgSource" alt="原始图片"/> <img id="imgCompress" alt="HTML5 Canvas压缩后的图片"/> <script> function compressImage(file) { if (!file || file.type.indexOf('image') != 0) return; //没有选中文件或者不是图片退出处理函数 var reader = new FileReader(); reader.onload = function (event) { var imgCompress = document.getElementById('imgCompress'), imgSource = document.getElementById('imgSource'); imgCompress.src = imgSource.src = event.target.result; //firefox12测试时发现不延时设置压缩数据,可能会无法获取到压缩数据,chrome测试没有问题。 setTimeout(function () { var quality = 30; //图像压缩比,越小压缩越多 imgCompress.src = jic.compress(imgCompress, quality); //压缩图像后重新设置内容 document.getElementById('dvRst').innerHTML = '压缩前大小:' + imgSource.src.length + '<br/>压缩后大小:' + imgCompress.src.length; //ajax发送imgCompress.src内容到服务器,服务器将base64内容转为2进制数据保存为图片即可。 }, 10); } reader.readAsDataURL(file); } </script> </body> </html>