首页 > 代码库 > js图片压缩上传
js图片压缩上传
最近公司的移动产品相约app要做一次活动,涉及到图片上传,图片又不能太大,不然用户体验太差,必须先压缩再上传,所以用到了html5的canvas和FileReader,代码先上,小弟前端经验不足,代码写得有点乱,有什么不足之处,望大神指点!
<div class="free-upload"> <p>上传您的约会照片,一张合影、一张票据哦!</p> <div class="free-upload-photo"> <span id="photo_img"></span> <input type="file" id="photo" /> </div> <div class="free-upload-bill"> <span id="bill_img"></span> <input type="file" id="bill" /> </div> <p id="photo_loading">正在上传...</p></div>
js用到了jquery
var photo = $(‘#photo‘);function isCanvasSupported(){ var elem = document.createElement(‘canvas‘); return !!(elem.getContext && elem.getContext(‘2d‘));}photo.on(‘change‘, function(event){ if(!canvasSupported){ return; } compress(event, function(base64Img){ $.ajax({ ‘url‘ : ‘/?s=free/upload‘, ‘type‘ : ‘post‘, ‘data‘ : {‘base64Img‘ : base64Img}, ‘success‘ : function(ret){ //拿到php传过来的图片地址 } }); });});function compress(event, callback){ var file = event.currentTarget.files[0]; var reader = new FileReader(); reader.onload = function (e) { var image = $(‘<img/>‘); image.on(‘load‘, function () { var square = 700; var canvas = document.createElement(‘canvas‘); canvas.width = square; canvas.height = square; var context = canvas.getContext(‘2d‘); context.clearRect(0, 0, square, square); var imageWidth; var imageHeight; var offsetX = 0; var offsetY = 0; if (this.width > this.height) { imageWidth = Math.round(square * this.width / this.height); imageHeight = square; offsetX = - Math.round((imageWidth - square) / 2); } else { imageHeight = Math.round(square * this.height / this.width); imageWidth = square; offsetY = - Math.round((imageHeight - square) / 2); } context.drawImage(this, offsetX, offsetY, imageWidth, imageHeight); var data = http://www.mamicode.com/canvas.toDataURL(‘image/jpeg‘);>
js图片压缩上传
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。