zoukankan      html  css  js  c++  java
  • JS—图片压缩上传(单张)

    *vue+webpack环境,这里的that指到vue实例

    
    <input type="file" name="file" accept="image/*" @change="selectImgs" ref="file" />
    

    一、图片压缩

    
        /*
            file:文件(类型是图片格式),
            obj:文件压缩后对象width, height, quality(0-1)
            callback:容器或者回调函数
        */
        photoCompress(file,obj,callback){
            let that=this;
            let ready=new FileReader();
            /*开始读取指定File对象中的内容. 读取操作完成时,返回一个URL格式的字符串.*/
            ready.readAsDataURL(file);
            ready.onload=function(){
                let re=this.result;
                that.canvasDataURL(re,obj,callback)  //开始压缩
            }
        },
    
    
    /*利用canvas数据化图片进行压缩*/
    /*图片转base64*/
        canvasDataURL(path, obj, callback){
            
            let img = new Image();
            img.src = path;
            img.onload = function(){
                let that = this;   //指到img
                // 默认按比例压缩
                let w = that.width,
                    h = that.height,
                    scale = w / h;
                w = obj.width || w;
                h = obj.height || (w / scale);
                let quality = 0.7;  // 默认图片质量为0.7
                //生成canvas
                let canvas = document.createElement('canvas');
                let ctx = canvas.getContext('2d');
                // 创建属性节点
                let anw = document.createAttribute("width");
                anw.nodeValue = w;
                let 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值越小,所绘制出的图像越模糊
                let base64 = canvas.toDataURL('image/jpeg', quality);
                // 回调函数返回base64的值
                callback(base64);
            }
        },
    
    

    二、base64转文件

    这里后台接口不支持base64,根据实际接口情况使用

    
        /*这里转blob*/
        base64UrlToBlob(urlData){
            let arr = urlData.split(','), 
            mime = arr[0].match(/:(.*?);/)[1],  // 去掉url的头,并转化为byte
            bstr = atob(arr[1]),    // 处理异常,将ascii码小于0的转换为大于0
            n = bstr.length, 
            u8arr = new Uint8Array(n);
            while(n--){
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], {type:mime});
            //转file
            //return new File([u8arr], filename, {type:mime});
        },
    

    三、上传图片

    
        selectImgs(e) {    //选择文件后执行
          let that=this
          let fileObj=e.target.files[0]  //获取file
          //console.log(fileObj)
          var form = new FormData();  // 创建FormData 对象
          if(fileObj.size/1024 > 1025) { //文件大于1M(根据需求更改),进行压缩上传
              that.photoCompress(fileObj, {   //调用压缩图片方法
                  quality: 0.2
              }, function(base64Codes){
                  //console.log("压缩后:" + base.length / 1024 + " " + base);
                  let bl = that.base64UrlToBlob(base64Codes);
                  //console.log(bl)
                  form.append("file", bl, "file_"+Date.parse(new Date())+".jpg"); // 文件对象
                  that.imgRequest(form);  //请求图片上传接口
              });
          }else{ //小于等于1M 原图上传
              form.append("file", fileObj); // 文件对象
              that.imgRequest(form);   //请求图片上传接口
          }
        },
    
    
         /*图片上传接口*/
        imgRequest(param){
          PostSaveImg(    //封装的ajax(axios)方法
              param
          ).then(data => {
              if (data.status === 200 || data.status === 304){
                let item={
                  path:this.imgpath+data.data[0].path,
                }
                let jsonitem={
                  jlid:this.jlid,
                  path:data.data[0].path,
                  xxdm:this.xxdm,
                }
                this.imglistJson.push(jsonitem)
                this.imglist.push(item)
              }else{
                 Toast({    //封装的提示方法
                    message: '图片上传失败',
                    position: 'middle',
                    duration: 2000
                  })
              } 
          })
          
          /*原生请求*/
          // const xhr = new XMLHttpRequest()   
          // xhr.open('POST', HOSTMOBILE+'api/mobile/xcjg/sctp', true)   //接口地址
          // xhr.send(param)
          //  xhr.onload = () => {
          //   if (xhr.status === 200 || xhr.status === 304) {
          //     let datas = JSON.parse(xhr.responseText)
          //     console.log('response: ', datas)
          //   } else {
          //     alert(`${xhr.status} 请求错误!`)
          //   }
          // }
          
        },
    

    其他

    element ui 图片上传组件(不包含压缩)

    来源:https://segmentfault.com/a/1190000015987551

  • 相关阅读:
    重写(Overriding)与重载(Overloading)的区别
    A Guide to setup SQL Server Reporting Services (SSRS) with Dynamics AX
    date2Str Function in Dynamics AX 2009
    浅谈程序员加薪问题(转)
    消息队列设计精要
    Redis集群模式原理探究
    SpringBoot内置tomcat原理分析
    Mybatis整体设计探究
    MapStruct 使用详解
    Zookeeper快速领导者选举原理
  • 原文地址:https://www.cnblogs.com/datiangou/p/10148619.html
Copyright © 2011-2022 走看看