最近有一个小项目,有这么一个需求,要把照片上传到服务器,可是现在手机照片都是几M几M的,所以必须压缩下,我百度来百度去,也问了下网友,终于,在网友的帮助下,写出来了..
下面先上个压缩效果图
然后上前端代码吧...
然后上前端代码吧...
然后上前端代码吧...
<body><img id="preview" src="" width="150" height="180" style="display: block; width: 150px; height: 180px;"><input type="file" name="file" id="doc" style="width:150px;" οnchange="javascript:setImagePreview();"><canvas id="cans" ></canvas><br><br><button>上传</button><br><br><br><br><br><br><div></div><script src="///jquery/3.0.0-beta1/jquery.js"></script><script type="text/javascript">//下面用于图片上传预览功能function setImagePreview(avalue) {var docObj=document.getElementById("doc");var imgObjPreview=document.getElementById("preview");if(docObj.files &&docObj.files[0]){//火狐下,直接设img属性imgObjPreview.style.display = 'block';imgObjPreview.style.width = '150px';imgObjPreview.style.height = '180px';//imgObjPreview.src = docObj.files[0].getAsDataURL();//火狐7以上版本不能用上面的getAsDataURL()方式获取,需要一下方式imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);}else{//IE下,使用滤镜docObj.select();var imgSrc = document.selection.createRange().text;var localImagId = document.getElementById("localImag");//必须设置初始大小localImagId.style.width = "150px";localImagId.style.height = "180px";//图片异常的捕捉,防止用户修改后缀来伪造图片try{localImagId.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;}catch(e){alert("您上传的图片格式不正确,请重新选择!");return false;}imgObjPreview.style.display = 'none';document.selection.empty();}return true;}$(document).ready(function(){$('button').click(function(){var img_this=new Image();img_this.src=$('#preview').attr('src');var width = img_this.width,height = img_this.height;var scale = width / height;// alert(width+"\r\n"+height+"\r\n"+scale);width1 = 300;height1 = parseInt(width1 / scale);var canvas = $("#cans");canvas[0].width = width1; canvas[0].height = height1;var ctx = canvas[0].getContext('2d');ctx.drawImage(img_this,0,0,width,height,0,0,width1,height1);var cropStr =canvas[0].toDataURL("image/jpeg",0.5);$('div').append("<p>"+cropStr+"</p>"); alert("1");$.ajax( { url:'../UserServlet?method=uploadImgs',// 发送Base64格式的字符串到后端,后端可以转化成图片的, data:{ img1:cropStr }, type:'post', cache:false, dataType:'json', success:function(data) { if(data.msg =="true" ){ // view("修改成功!"); alert("修改成功!"); window.location.reload(); }else{ view(data.msg); } }, error : function() { // view("异常!"); alert("异常!"); } });})})</script>
代码太多了,解释下核心思想吧..
主要想法就是先把图片画在canvas上,然后toDataUrl转化为Base64编码的字符串,然后把这个东西发到后台,就可以得到图片了,非常好用
下面是核心代码,
var img_this=new Image();img_this.src=$('#preview').attr('src');
var width = img_this.width,height = img_this.height;var scale = width / height;// alert(width+"\r\n"+height+"\r\n"+scale);width1 = 300;height1 = parseInt(width1 / scale);var canvas = $("#cans");canvas[0].width = width1; canvas[0].height = height1;var ctx = canvas[0].getContext('2d');ctx.drawImage(img_this,0,0,width,height,0,0,width1,height1);var cropStr =canvas[0].toDataURL("image/jpeg",0.5);
cropStr就是Base64编码的图片哦..
下面在来一段后台转码的代码吧
package sys.nit.djt.serviece;import java.io.FileOutputStream;import java.io.OutputStream;import Decoder.BASE64Decoder;public class Base64ToImg {//base64字符串转化成图片 public static boolean GenerateImage(String imgStr) { //对字节数组字符串进行Base64解码并生成图片 if (imgStr == null) //图像数据为空 return false; BASE64Decoder decoder = new BASE64Decoder(); try { //Base64解码 byte[] b = decoder.decodeBuffer(imgStr); for(int i=0;i<b.length;++i) { if(b[i]<0) {//调整异常数据 b[i]+=256; } } //生成jpeg图片 String imgFilePath = "d://222.jpg";//新生成的图片 OutputStream out = new FileOutputStream(imgFilePath);out.write(b); out.flush(); out.close(); return true; } catch (Exception e) { return false; } } }
如果觉得《微信手机网页上传图片高效率压缩(Canvas+Base64)》对你有帮助,请点赞、收藏,并留下你的观点哦!