孙肖宁

javascript实现对图片的压缩预览
首先引入jquery<script src="https://cdn.bootcss.com/jq...
扫描右侧二维码阅读全文
06
2018/12

javascript实现对图片的压缩预览

  1. 首先引入jquery

    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
  2. 准备html标签

    <input type="file" id="picFile" onchange="readFile(this)"/>
    <img style="" id="img" src="" alt="" />
  3. javascript代码用户图片的压缩

    function readFile(obj){
     var file = obj.files[0];
     //判断类型是不是图片
       if(!/image\/\w+/.test(file.type)){
           alert("你上传的不是图片");
           return false;
       }
       var reader = new FileReader();
       reader.readAsDataURL(file);
       reader.onload = function(e){
           dealImage(this.result,{width:200},function(base){
               document.getElementById('img').setAttribute('src',base)
           });
       }
     }
     //PC端传入的可以是相对路径,但是移动端必须是绝对路径
     //callback 回调函数,必须带有base64字符串的参数
     //obj 可选值width, height, quality
    function dealImage(path, obj, callback){
       var img = new Image();
       img.src = path;
       img.onload = function(){
           var that = this;
           // 默认按比例压缩
           var w = that.width,
               h = that.height,
               scale = w / h;
           w = obj.width || w;
           h = obj.height || (w / scale);
           var quality = 1; // 值越大越清楚
           //生成canvas
           var canvas = document.createElement('canvas');
           var ctx = canvas.getContext('2d');
           // 创建属性节点
           var anw = document.createAttribute("width");
           anw.nodeValue = w;
           var anh = document.createAttribute("height");
           anh.nodeValue = h;
           canvas.setAttributeNode(anw);
           canvas.setAttributeNode(anh);
           ctx.drawImage(that, 0, 0, w, h);
           // 图像质量
           if(obj.quality && obj.quality <= 1 && obj.quality > 0){
               quality = obj.quality;
           }
           // quality值越小,所绘制出的图像越模糊
           var base64 = canvas.toDataURL('image/jpeg', quality );
           // 回调函数返回base64的值
           callback(base64);
       }
     }
Last modification:December 7th, 2018 at 03:46 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment