js上传图片,利用canvas实现图片压缩

飞翔的鱼 2019-07-01

最近项目中的一个基础功能-----手机上传图片
技术栈:
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});
  }

相关推荐