注册 登录 充值会员 退出
网站、APP、小程序等定制开发,联系QQ 1206995177 毕业设计 java源码 PHP源码

充值

HTML5+jQuery图片上传压缩预览代码

作者/代码整理:  (源码已亲测,不会安装的可以向QQ1915635791要安装视频教程) 发布日期:2023-12-20
HTML5+jQuery图片上传压缩预览代码
一款强大的HTML5+jQuery图片上传压缩预览代码,上传图片并压缩显示。


js代码

<script>
  (function ($) {
    $.extend({
      //压缩图片,参数1:file对象,参数2:压缩比例
      compress(file,scale) {
        return new Promise(function (resolve,reject) {
          let _scale=scale || 1;
          let cvs = document.createElement('canvas');
          let ctx = cvs.getContext('2d');
          let img = new window.Image();
          let imgType=file.type;
          img.src = URL.createObjectURL(file);
          img.onload=function () {
            cvs.width = img.width*_scale;
            cvs.height = img.height*_scale;
            ctx.drawImage(img, 0, 0, cvs.width, cvs.height);
            resolve(cvs.toDataURL(imgType));
          }
        });
      }
    });
    $.fn.extend({

      //复制节点
      cloneNode(num){
        let p=this.parent();
        for (let i=0;i<num;i++){
          p.append(this.clone(true))
        }
      }
    });
    $(function () {
      $('li').cloneNode(6);//复制66个节点
      //点击触发input
      $('li').each(function (i) {
        $(this).click(function () {
          $('input').attr("name",'input_'+i).click();
        })
      });

      $("input").change(function () {
        let files=$(this)[0].files[0];//获取files对象
        let index=parseInt(($(this).attr('name')).split("_")[1]);
         //0.5为当前压缩比
        $.compress(files,0.5).then((url)=>{
          $('li').eq(index).css({"background-image": "url("+url+")"});
		  //上传到服务器
		  $.post('url',{base64:url},()=>{
			
		  })
        })
      })
    })
  })(jQuery)
</script>