12上传您的约会照片,一张合影、一张票据哦!
34 5 678 9 1011正在上传...
12
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 = $('');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实现客户端压缩图片功能