zoukankan      html  css  js  c++  java
  • js实现本地的图片压缩上传预览

    js在设计时考虑到安全的原因是不允许读写本地文件的,随着html5的出现提供了fileReader AP从而可以I实现本地图片的读取预览功能,

    另外在移动端有的限制图片大小的需求,主要是考虑图片过大会占用带宽,严重拖慢浏览速度,所以需要进行前端的压缩,主要通过html5的canvas来实现,

    代码入下:

    HTML:

    <h3>上传图片</h3>
    <ul class="list">
        <li class="upload">
            <input type="file" class="chose" accept="image/*" multiple/>
            <img src="img/weituo_luru_add.png" />
        </li>
    </ul>

    CSS:

    * {
        padding: 0;
        margin: 0;
    }
    h3{
        font-size: 0.6rem;
        font-weight: normal;
        padding: 0.4rem 0.6rem;
    }
    .list {
        margin-left: 0.4rem;
        margin-top: 0.4rem;
        overflow: hidden;
    }
                
    .list li {
        float: left;
        width: 2.76rem;
        height: 2.76rem;        
            margin-right: 0.4rem;
        position: relative;
        list-style: none;
    }
                
    .list img {
        width: 100%;
        height: 100%;
    }
                
    .upload input {
        width: 100%;
        height: 100% ;
        opacity: 0;
        position: absolute;
        top: 0 ;
        left: 0 ;
        right: 0 ;
        bottom: 0 ;
        z-index: 10;
        transform: translateY(0) ;
    }
                
    .upload img {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
    }
                
    #upcancle {
        position: absolute;
        right: 0;
        width: 0.6rem;
        height: 0.6rem;
        text-align: center;
        line-height: 0.6rem;
        background-color: #00D3AF;
        color: #f3f3f3;
        border: solid 0.02rem #00D3AF;
        font-size: 0.5rem;
        border-radius: 50%;
        z-index: 8;
        font-weight: bold;
    }    

    JS:

    var reader = new FileReader();
        //创建一个img对象
    var img = new Image();
        // 选择的文件对象
    var file = null;
         // 缩放图片需要的canvas
    var canvas = document.createElement('canvas');
     var context = canvas.getContext('2d');
    
         // base64地址图片加载完毕后
    img.onload = function() {
        // 图片原始尺寸
        var originWidth = this.width;
        var originHeight = this.height;
          // 最大尺寸限制,可通过国设置宽高来实现压缩程度
        var maxWidth = 800,
           maxHeight = 800;
          // 目标尺寸
       var targetWidth = originWidth,
           targetHeight = originHeight;
          // 图片尺寸超过400x400的限制
        if(originWidth > maxWidth || originHeight > maxHeight) {
            if(originWidth / originHeight > maxWidth / maxHeight) {
               // 更宽,按照宽度限定尺寸
                 targetWidth = maxWidth;
                  targetHeight = Math.round(maxWidth * (originHeight / originWidth));
             } else {
                 targetHeight = maxHeight;
                 targetWidth = Math.round(maxHeight * (originWidth / originHeight));
              }
        }
          // canvas对图片进行缩放
          canvas.width = targetWidth;
           canvas.height = targetHeight;
          // 清除画布
          context.clearRect(0, 0, targetWidth, targetHeight);
          //画布背景色改为白色,默认是黑色,如果上传的是圆形图片会背景有黑色块
         context.fillStyle = '#fff';
          context.fillRect(0, 0, targetWidth, targetHeight);
            // 图片压缩                
          context.drawImage(img, 0, 0, targetWidth, targetHeight);
    
           /*第一个参数是创建的img对象;第二个参数是左上角坐标,后面两个是画布区域宽高*/
           //压缩后的图片base64 url
            /*canvas.toDataURL(mimeType, qualityArgument),mimeType 默认值是'image/jpeg';
             * qualityArgument表示导出的图片质量,只要导出为jpg和webp格式的时候此参数才有效果,默认值是0.92*/
          var newUrl = canvas.toDataURL('image/jpeg', 0.92); //base64 格式
    
            //显示压缩后的图片
           var li = '<li><span id="upcancle">X</span><img src="' + newUrl + '"/></li>';
              $('.list').prepend(li);
    };
        //input type='file'上传时执行的函数
     $('.chose').change(function() {
        file = this.files[0];
         // 选择的文件是图片                
        if(this.files && this.files[0]) {
             var ext = this.value.substring(this.value.lastIndexOf(".") + 1).toLowerCase();
             if(ext != 'png' && ext != 'jpg' && ext != 'jpeg') {
                  alert("图片的格式必须为png或者jpg或者jpeg格式!");
                  return false;
             } else {
                   reader.readAsDataURL(file);
              }
        }
    })
     // 文件base64化,以便获知图片原始尺寸
    reader.onload = function(e) {
           img.src = e.target.result;
    };
    
    //删除按钮
    $('.list').delegate('span', 'click', function() {
          $(this).parents('li').remove();
    })
  • 相关阅读:
    [C++11新特性] weak_ptr和unique_ptr
    [C++11新特性] shared_ptr共享的智能指针
    VS2019 Qt5.15.2 开发环境搭建
    【C++11 新特性】Lambda表达式(三)
    【C++11 新特性】bind(二)
    【C++11 新特性】function(一)
    【IPC 进程间通信】有名管道的简单实现
    【IPC 进程间通信】常用进程间通信方式总结
    Qt 文件常见操作管理类
    【GitHub 开源分享】QML 在线预览工具
  • 原文地址:https://www.cnblogs.com/web-wjg/p/9210411.html
Copyright © 2011-2022 走看看