前端js实现上传图片大于2M时压缩,预览

您所在的位置:网站首页 大于30k小于2m是多大 前端js实现上传图片大于2M时压缩,预览

前端js实现上传图片大于2M时压缩,预览

2023-07-02 18:18| 来源: 网络整理| 查看: 265

最近有个需求,用户在上传图片预览时,需要显示大小为2M以下,大于2M的需要压缩后上传,小于2M的原图显示 一.先说下限制图片大小的好处 直接上传特别占用带宽,上传速度慢,对程序考验以及影响用户的体验图片资源直接上传,占用的服务器空间过大,容易造成空间浪费  二.实现思路

只要是借用canvas和FileReader函数,以下是代码,其中添加了需求,大于2M的图片才进行压缩,小于的原图显示

html文件

css文件

div#previewImg{ background: #eeeeee; width: 400px; height: 300px; display: table-cell; vertical-align: middle; text-align: center; } #previewImg img{ max-width: 100%; max-height: 100%; display: block; } #upload{ margin-bottom: 20px; }

js文件,重头戏

$(function () { $('#upload').on('change',function () { var filePath = $(this).val(), //获取input的value,里面是文件的路径 fileFormat = filePath.substring(filePath.lastIndexOf('.')).toLowerCase(), imgBase64 = '', //存储图片的base64 maxSize = 2*1024*1024, fileObj = document.getElementById('upload').files[0]; //上传文件的对象,要这样写才行,用jquery写法获取不到对象 console.log(fileObj.size) //检查文件格式 if(!fileFormat.match(/.png|.jpg|.jpeg|.gif/)){ alert('文件类型错误,文件格式必须为:png/jpg/jpeg!') return; } if(fileObj.size > maxSize){ //调用函数,对图片进行压缩 compress(fileObj,function (imgBase64) { imgBase64 = imgBase64; $('#viewImg').attr('src',imgBase64); }) }else{ directTurnIntoBase64(fileObj,function (imgBase64) { imgBase64 = imgBase64; $('#viewImg').attr('src',imgBase64); console.log('大小没超过2M,不同进行压缩') }); } }); //不对图片进行压缩 function directTurnIntoBase64(fileObj,callback) { var r = new FileReader(); //转成base64 r.onload = function () { imgBase64 = r.result; // console.log(imgBase64); callback(imgBase64) } r.readAsDataURL(fileObj);//转成base64格式 } //对图片进行压缩 function compress(fileObj,callback) { if(typeof (FileReader) === 'undefined'){ console.log("当前浏览器内核不支持base64图片压缩") directTurnIntoBase64(fileObj,callback); }else{ try{ var reader = new FileReader(); reader.onload = function (e) { var image = $(''); image.load(function () { var squareW = 700,//定义画布大小,也就是图片压缩之后的像素 squareH = 600, canvas = document.createElement('canvas'), context = canvas.getContext('2d'), imageWidth = 0, //压缩图片大小 imageHeight = 0, offsetX = 0, offsetY = 0, data = ''; canvas.width = squareW; canvas.height = squareH; context.clearRect(0,0,squareW,squareH); if(this.width > squareW){ imageWidth = Math.round(squareW); imageHeight = squareH; offsetX = Math.round((imageWidth-squareW)/2); }else{ imageHeight = Math.round(squareH); imageWidth = squareW; offsetY = Math.round((imageHeight - squareH)/2) } context.drawImage(this,offsetX,offsetY,imageWidth,imageHeight); var data = canvas.toDataURL('image/jpeg') callback(data) }); image.attr('src',e.target.result) }; reader.readAsDataURL(fileObj); }catch (e) { console.log('压缩失败!') //调用不压缩方法 directTurnIntoBase64(fileObj,callback) } } } })  三.注意

本demo 只适用于ie10以上的浏览器,对于ie9中,不兼容

fileObj = document.getElementById('upload').files[0];

因为ie9中无法识别files属性,并且非IE6版本的IE由于安全问题直接设置img的src无法显示本地图片,但是可以通过滤镜来实现

//判断ie类型 var isIE = navigator.userAgent.match(/MSIE/) != null, isIE6 = navigator.userAgent.match(/MSIE 6.0/) != null; //根据浏览器的类型进行操作方式的选择 if(isIE) { //选中表单提交中的file对象,即获得焦点,可以继续保持 file.select(); //因为ie9安全级别高,需要模拟让其失去焦点 //file.blur(); //获取文件的本地地址 var reallocalpath = document.selection.createRange().text; //document.selection.createRange(); --->window.getSelection(); [ie11] //alert(reallocalpath); //IE6浏览器设置img的src为本地路径可以直接显示图片 if(isIE6){ //加载预览图 pic.src = reallocalpath; }else{ //alert('this'); //非IE6版本的IE由于安全问题直接设置img的src无法显示本地图片,但是可以通过滤镜来实现 document.getElementById("file1").value=reallocalpath; pic.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src=\"" + reallocalpath + "\")"; //pic.style.cssText="display: block;width:106px ;height: 130px;margin: 0 auto;"; //设置img的src为base64编码的透明图片 取消显示浏览器默认图片 pic.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='; //alert(reallocalpath); pic.src=reallocalpath; } }else { html5Reader(file); }

 

 以上是本渣搜了好多资料总结的

其中代码可用github上下载

地址:https://github.com/Clara07/imgDemo

关于ie9一下的兼容,可以参考下https://blog.csdn.net/qq_21987433/article/details/78280405这篇文章

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3