栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

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

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

技术栈:

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 和其它一些问题。这可能会让人沮丧,但你要尽量保持冷静,并系统地去思考。记住实践是解决问题的最佳方法。

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/245168.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号