无组件客户端js图片压缩

 1 <div class="free-upload">
 2     <p>上传您的约会照片,一张合影、一张票据哦!</p>
 3     <div class="free-upload-photo">
 4         <span id="photo_img"></span>
 5             <input type="file" id="photo" />
 6         </div>
 7         <div class="free-upload-bill">
 8             <span id="bill_img"></span>
 9         <input type="file" id="bill" />
10     </div>
11     <p id="photo_loading">正在上传...</p>
12 </div>
 1 var photo = $('#photo');
 2 
 3 function isCanvasSupported(){
 4     var elem = document.createElement('canvas');
 5     return !!(elem.getContext && elem.getContext('2d'));
 6 }
 7 
 8 photo.on('change', function(event){
 9     if(!canvasSupported){
10         return;
11   }
12       
13     compress(event, function(base64Img){
14       $.ajax({
15       'url' : '/?s=free/upload',
16       'type' : 'post',
17       'data' : {'base64Img' : base64Img},
18             'success' : function(ret){
19                      //拿到php传过来的图片地址
20         }
21      });
22    });
23 });
24 
25 function compress(event, callback){
26     var file = event.currentTarget.files[0];
27     var reader = new FileReader();
28 
29     reader.onload = function (e) {
30 
31         var image = $('<img/>');
32         image.on('load', function () {
33              var square = 700;
34              var canvas = document.createElement('canvas');
35 
36              canvas.width = square;
37              canvas.height = square;
38 
39              var context = canvas.getContext('2d');
40              context.clearRect(0, 0, square, square);
41              var imageWidth;
42              var imageHeight;
43              var offsetX = 0;
44              var offsetY = 0;
45 
46             if (this.width > this.height) {
47                   imageWidth = Math.round(square * this.width / this.height);
48                   imageHeight = square;
49                  offsetX = - Math.round((imageWidth - square) / 2);
50            } else {
51                  imageHeight = Math.round(square * this.height / this.width);
52                  imageWidth = square; 
53                  offsetY = - Math.round((imageHeight - square) / 2); 
54            }
55 
56             context.drawImage(this, offsetX, offsetY, imageWidth, imageHeight);
57             var data = canvas.toDataURL('image/jpeg');
58             callback(data);
59          });
60 
61           image.attr('src', e.target.result);
62        };
63  
64      reader.readAsDataURL(file);
65 }

js通过html5里面的canvas实现客户端压缩图片功能

posted @ 2016-12-28 17:06  zhangkui  阅读(192)  评论(0编辑  收藏  举报