js圖片壓縮上傳

來源:互聯網
上載者:User

標籤:

最近公司的移動產品相約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 = canvas.toDataURL(‘image/jpeg‘);            callback(data);         });          image.attr(‘src‘, e.target.result);       };      reader.readAsDataURL(file);}                         

  

    

js圖片壓縮上傳

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.