$('input[type="file"]').change(function(event) { var currentTarget = event.currentTarget; var currentFile = currentTarget.files[0]; var fr = new FileReader(); var img = new Image(); fr.onload = function() { img.src = this.result; img.onload = function() { var imgData = self.compressWithRatio(img, { maxWidth: 780, maxHeight: 1560, quality: 1 }); self.uploadFile(imgData); }; }; fr.readAsDataURL(currentTarget.files[0]); }); ===================================== compress: function(img, width, height, quality) { // var orient = this.getPhotoOrientation(img); var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); if (width > height) { canvas.width = height; canvas.height = width; ctx.save(); ctx.translate(height / 2, width / 2); ctx.rotate(90 * Math.PI / 180); ctx.drawImage(img, -width / 2, -height / 2, width, height); ctx.restore(); } else { canvas.width = width; canvas.height = height; ctx.drawImage(img, 0, 0, width, height); } // 针对iphone照片自动旋转 兼容处理 // canvas.width = width; // canvas.height = height; // if (orient == 6) { // ctx.save(); // ctx.translate(width / 2, height / 2); // ctx.rotate(90 * Math.PI / 180); // ctx.drawImage(img, -height / 2, -width / 2, height, width); // ctx.restore(); // } else { // ctx.drawImage(img, 0, 0, width, height); // } return canvas.toDataURL('image/jpeg', quality || 0.6); }, ===================================== compressWithRatio: function(img, settings) { var maxWidth, maxHeight; var w = img.width; var h = img.height; // 调整宽度 if ((maxWidth = settings.maxWidth) > 0 && w > maxWidth) { h = maxWidth / w * h; w = maxWidth; } // 调整高度 if ((maxHeight = settings.maxHeight) > 0 && h > maxHeight) { w = maxHeight / h * w; h = maxHeight; } return this.compress(img, w, h, settings.quality); }, getPhotoOrientation: function(img) { var orient; EXIF.getData(img, function() { orient = EXIF.getTag(this, 'Orientation'); }); return orient; }, uploadFile: function(imgIndex, imgData) { var formData = new FormData(); formData.append('imageData', imgData); formData.append('activityId', gactivityId); formData.append('mobilePhone', mobilePhone); formData.append('imageName', imgIndex); $.ajax({ url: uploadFileUrl, type: 'post', data: formData, processData: false, contentType: false, dataType: 'json', success: function(result) { if (result.success) { tank.errorTips("保存成功"); } else { tank.errorTips(result.error_msg); } }, error: function() { tank.errorTips("服务器错误"); } }); },