H5 压缩图片上传(pc端适用)支持png/jpg格式(其他格式都会转为png)

来源:互联网 发布:手机淘宝助理在哪里找 编辑:程序博客网 时间:2024/05/17 09:37

转载自:http://blog.csdn.net/limyrain/article/details/51497589

[html] view plain copy
  1. html代码:  
  2. <pre name="code" class="html"><!DOCTYPE html>  
  3. <html lang="en">  
  4.     <head>  
  5.         <meta charset="utf-8">  
  6.         <script src="js/jquery.js"></script>  
  7.         <script src="js/jquery-ui.js"></script>  
  8.         <script src="js/upload/jquery.fileupload.js"></script>  
  9.         <script src="js/upload/preview.js"></script>  
  10.     </head>  
  11.     <body style="background:#000; color:#FFF">  
  12.     <div>  
  13.         <input hidden="hidden" id="fileId" type="file" name="imgFile" accept="image/*" />  
  14.         <div id="progress" class="overlay"/></div>  
  15.     </div>  
  16.     <div id="picId" title="点击选择图片" onclick="$('#fileId').click();">  
  17.     <img src="addimg.jpg">  
  18.     </div>  
  19.     <button type="button" onclick="uploadImage()">确定</button>  
  20.     </body>  
  21. </html>  

js:(设置宽高就压缩指定大小,不设置就原大小)

[javascript] view plain copy
  1. <script type="text/javascript">  
  2.     //图片压缩  
  3. $('#fileId').fileupload({  
  4.       dropZone:null,  
  5.       pasteZone:null,  
  6.       add: function (e, data) {  
  7.         if($.support.localPreview){  
  8.           var file = data.files[0];  
  9.           $(this).previewImg({  
  10.             uploadFile: file,   
  11.             uploadData: data,  
  12.             divName:'picId',  
  13.             fileName:'picId',  
  14.              width: 118,  
  15.             height: 40,   
  16.             quality: 90,  
  17.           });  
  18.         }else{  
  19.           if (e.isDefaultPrevented()) {  
  20.             return false;  
  21.           }  
  22.         }  
  23.       },  
  24.     }).prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled');  
  25.   
  26.    function uploadImage() {  
  27.     alert($("#bigPreviewImgpicId").attr("src"));  
  28.     var img = $("#bigPreviewImgpicId").attr("src");  
  29.     $.ajax({  
  30.         type : "POST",  
  31.         url : "footerConfig.action?action=saveImg",  
  32.         data : {  
  33.             base64Data : img  
  34.         },  
  35.         cache : false,  
  36.         success : function(data) {  
  37.             alert("上传成功");  
  38.         },  
  39.         error : function(XMLHttpRequest, textStatus, errorThrown) {  
  40.             alert("上传失败,请检查网络后重试");  
  41.         }  
  42.     });  
  43. }  
  44.    </script>  


preview.js(此处是将别人发给我参考代码的稍加修改,做成了兼容png格式图片,原地址不详。)

[javascript] view plain copy
  1. ;(function ($) {  
  2.   "use strict";  
  3.   $.support.localPreview = !!(window.FileReader && window.Image && document.createElement('canvas').getContext);  
  4.   var defaults = {  
  5.      uploadFile: null,  
  6.      uploadData: null,  
  7.      width: null,  
  8.      height: null,  
  9.      resizable: false,  
  10.      selectable: false,  
  11.      avatarParams: {},  
  12.      padding:0,  
  13.      afterOpen: function(modal) {  
  14.       //do your stuff  
  15.      },  
  16.      afterClose: function(modal) {  
  17.       //do your suff  
  18.      }  
  19.   };  
  20.   var config = {};  
  21.   var jcrop = null;  
  22.   var $this = new Object();  
  23.   var methods = {  
  24.     init : function(options) {  
  25.           
  26.         //alert(options.divName);  
  27.         var DivName=options.divName;  
  28.         var fileName=options.fileName;  
  29.         return this.each(function() {  
  30.             $this.uploader = $(this);  
  31.             $this =  $.extend({}, $this, methods);  
  32.             config = $.extend({}, defaults, options);  
  33.   
  34.             var reader = new FileReader();  
  35.             var file = config.uploadFile;  
  36.             if(file == null){  
  37.               $.error( 'uploadFile is not setted!' );  
  38.             }  
  39.             reader.onload = function(e) {  
  40.                 $this.compress(e.target.result, options.quality, file.type,options.width,options.height, function(compressedSrc){  
  41.                  var $img = $('<img>').attr("src", compressedSrc);  
  42.                   $img.attr('id''bigPreviewImg'+fileName+'');  
  43.                   $('#bigPreviewImg'+fileName).css({  
  44.                       width:'300px',  
  45.                   });  
  46.                    
  47.                   $('#'+DivName).empty().append($img);  
  48.                 });                  
  49.             },  
  50.             reader.readAsDataURL(file);  
  51.         });  
  52.     },  
  53.   
  54.     compress: function(src, quality, mime_type,width,height, callback){  
  55.       var image = new Image();  
  56.       image.src = src;   
  57.   
  58.       image.onload = function () { // binding onload event    
  59.         var imgWidth = image.naturalWidth;  
  60.         var imgHeight = image.naturalHeight;  
  61.         var canvas = document.createElement('canvas');  
  62.        /* if(imgHeight > 400) {  
  63.           imgWidth *= 400 / imgHeight;  
  64.           imgHeight = 400;  
  65.         } */  
  66.         var ctx = canvas.getContext("2d");  
  67.         ctx.clearRect(0, 0, canvas.width, canvas.height);   
  68.         canvas.width = (undefined==width)?imgWidth:width;  
  69.         canvas.height = (undefined==height)?imgHeight:height;  
  70.         ctx.drawImage(image, 0, 0, canvas.width, canvas.height);  
  71.         mime_type = (undefined==mime_type) ? "image/jpeg" : mime_type;  
  72.         quality = (undefined==quality)?"100" : quality;  
  73.         var newImageData = canvas.toDataURL(mime_type, quality/100);  
  74.   
  75.         if(undefined !== callback){  
  76.           callback(newImageData);  
  77.         }  
  78.       };  
  79.     },  
  80.    
  81.   };  
  82.   
  83.   $.fn.previewImg = function(method) {  
  84.     if ( methods[method] ) {    
  85.       return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));    
  86.     } else if ( typeof method === 'object' || ! method ) {  
  87.       return methods.init.apply( this, arguments );    
  88.     } else {    
  89.       $.error( 'Method ' +  method + ' does not exist' );    
  90.     }  
  91.   };  
  92. })(jQuery);  


样式:

上传前:


压缩后:(注:此时只是压缩后图片的现实,并没有上传到服务器。我是将得到的base64传到后台,在后台解析上传。后台操作此处没有记录)


代码下载地址:http://download.csdn.net/detail/limyrain/9530715


0 0