第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定

JS上傳圖片,利用canvas實現(xiàn)圖片壓縮

標簽:
JavaScript

项目中的一个基础功能-----手机上传图片

技术栈:

1、利用canvas进行压缩(这个应该都比较熟悉)
2、利用exif-js获取照片旋转角度属性,因为有些手机机型会因为拍照时手机的方向使拍的照片带一个旋转角度的属性

核心代码:

var _orientation; //照片角度属性
EXIF.getData(fileInput, function () {
    _orientation = EXIF.getTag(fileInput, 'Orientation');
});
let reader = new FileReader();
reader.readAsDataURL(fileInput);
reader.onload = function (e) {
    var image = new Image();
    image.src = e.target.result;
    image.onload = function () {
      var canvas = document.createElement("canvas"); //创建临时画布
      var _width = this.width, _height = this.height, _ratio = _height / _width;
      //等比压缩
      if (this.width > 800) {
        _width = 800;
        _height = 800 * _ratio;
      }    
      canvas.width = _width;
      canvas.height = _height;
      var ctx = canvas.getContext("2d");
      switch (_orientation) {
        case 6:     // 旋转90度
          canvas.width = _height;
          canvas.height = _width;
          ctx.rotate(Math.PI / 2);
          ctx.drawImage(this, 0, -_height, _width, _height);
          break;
        case 3:     // 旋转180度
          ctx.rotate(Math.PI);
          ctx.drawImage(this, -_width, -_height, _width, _height);
          break;
        case 8:     // 旋转-90度
          canvas.width = _height;
          canvas.height = _width;
          ctx.rotate(3 * Math.PI / 2);
          ctx.drawImage(this, -_width, 0, _width, _height);
          break;
        default:
          ctx.drawImage(this, 0, 0, _width, _height);
      }
      //需要上传的数据对象
      const resultBase =dataURItoBlob(canvas.toDataURL("image/jpeg", 0.9));
      //...省略进行上传操作代码
    };
}
//将dataURI转成Blob用于上传
dataURItoBlob:function(dataURI) {
    // convert base64/URLEncoded data component to raw binary data held in a string
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
      byteString = atob(dataURI.split(',')[1]);
    else
      byteString = unescape(dataURI.split(',')[1]);

    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
    }
    return new Blob([ia], {type:mimeString});
  }


你会经常地遇到 bug 和其它一些问题。这可能会让人沮丧,但你要尽量保持冷静,并系统地去思考。记住实践是解决问题的最佳方法。

我们采集的是石头,但是必须时刻展望未来的大教堂。

點擊查看更多內(nèi)容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優(yōu)質(zhì)文章

正在加載中
  • 推薦
  • 1
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優(yōu)惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號

舉報

0/150
提交
取消