cropper+jq(图片裁剪上传)

  <link rel="stylesheet" href="../../cropper/cropper.css"> 
  <script type="text/javascript" src="../../cropper/cropper.js"></script> 

没有引入jquery的原因
cropper+jq(图片裁剪上传)_第1张图片

引入jquery

  <script src="../jquery-1.10.2.js"></script>

cropper+jq(图片裁剪上传)_第2张图片
cropper+jq(图片裁剪上传)_第3张图片
这里使用的是3.1.5版本


<!-- 用一个块元素(容器)包装图像或画布元素 -->
<div class="box">
    <img id="image" src="../img/act.png">
</div>
 $('#image').cropper({
      aspectRatio: 1 / 1,
      viewMode: 1,
      crop: function (e) {
        console.log(e);
      }
    });

示例

cropper+jq(图片裁剪上传)_第4张图片

父页面
 <!-- logo -->
                    <div class="layui-row" style="margin-bottom: 8px;">
                      <div class="layui-col-md12">
                        <div class="layui-form-item">
                          <label class="layui-form-label">logo:</label>
                          <div class="upload_reveal">上传图片
                            <input type="file" class="upload_file" id="coverImage" name="coverImage" />
                          </div>
                        </div>
                        <div class="layui-form-item" id="coverImageContent" style="padding-top: 10px">

                        </div>
                      </div>
                    </div>
  // logo--图片回调
    function setImg (url) {
      coverImageUrl = url;
      var html = '';
      $("#coverImageContent").html(html);
    }


    // 删除图片
    $('#coverImageContent').on('click', '.delImg', function (event) {
      event.stopPropagation();//阻止事件冒泡
      var that = $(this);
      layer.confirm('确定删除图片吗?', function (index) {
        // 最后去删除元素,否则找不到
        var delItem = that.parent();
        delItem.remove();
        layer.close(index);
        layer.msg('删除成功')
        coverImageUrl = "";
      });
    })

    var coverImage = document.getElementById('coverImage');
    coverImage.onchange = function () {
      var fileData = this.files[0];//这是我们上传的文件
      console.log('这是我们上传的文件fileData', this.files, fileData);
      console.log('ocument.getElementById("coverImage").value', document.getElementById("coverImage").value);

      var aa = document.getElementById("coverImage").value.toLowerCase().split('.'); //以“.”分隔上传文件字符串
      // var aa=document.form1.userfile.value.toLowerCase().split('.');//以“.”分隔上传文件字符串

      if (document.getElementById("coverImage").value == "") {
        layer.msg('图片不能为空!');
        return;
      } else {
        if (aa[aa.length - 1] == 'gif' || aa[aa.length - 1] == 'jpg' || aa[aa.length - 1] == 'bmp'
          ||
          aa[aa.length - 1] == 'png' || aa[aa.length - 1] == 'jpeg') //判断图片格式
        {
          var imagSize = document.getElementById("coverImage").files[0].size;

          if (imagSize < 1024 * 1024 * 3) {
            console.log('fileData', fileData); 
            
            //读取上传文件
            let reader = new FileReader();
            //readAsDataURL方法可以将File对象转化为data:URL格式的字符串(base64编码)
            reader.readAsDataURL(fileData);

            reader.onload = (e) => {
              let dataURL = reader.result;
              console.log('dataURL', dataURL);

              window.sessionStorage.setItem('coverImage', dataURL); 
              layer.open({
                title: '编辑图片',
                type: 2,
                scrollbar: true,
                area: ['60%',
                  '80%'],
                content: './imgEdit.html?fileName=' + fileData.name,
                // content: './imgEdit.html',
                end: function () { 
                } 
              });
            } 
          } else {
            layer.msg("图片大小不能超过3M!");
          }
        } else {
          layer.msg('请选择格式为*.jpg、*.gif、*.bmp、*.png、*.jpeg 的图片'); //jpg和jpeg格式是一样的只是系统Windows认jpg,Mac OS认jpeg,
        }
      }
    }


弹窗页面
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>编辑图片</title>
  <link rel="stylesheet" href="../../layuiadmin/layui/css/layui.css">
  <link rel="stylesheet" href="../../layuiadmin/style/admin.css">
  <link rel="stylesheet" href="../open.css">
  <link rel="stylesheet" href="../../cropper/cropper.css">
  <style>
    #coverImageContent {
      width: 500px;
      height: auto;

    }

    #cropImg {
      width: 500px;
      height: 500px;
    }

    .previewBox {
      /* box-shadow: 0 0 5px #adadad; */

      width: 200px;
      height: 200px;
      margin-top: 30px;
      overflow: hidden;
      /*这个超出设置为隐藏很重要,否则就会整个显示出来了*/
    }

    .previewImg {
      width: 200px;
      height: 200px;
    }
  </style>
</head>

<body>

  <div class="layui-fluid">
    <div class="layui-row layui-col-space15">
      <div class="layui-col-md12">
        <form class="layui-form layui-form-pane" action="">
          <!-- logo -->
          <div class="layui-row">
            <div class="layui-col-md6">

              <div class="layui-form-item" id="coverImageContent" style="padding-top: 10px">
                <img src="" alt="" id="cropImg">
              </div>
            </div>

            <div class="layui-col-md6"
              style="display: flex;flex-direction: column;justify-content: center;align-items: center;">
              <div class="title" style="margin-bottom: 50px;margin-top: 10px;font-size: 18px;">裁剪预览</div>
              <!-- 3.两个用于预览的div  -->
              <div class="previewBox">
              </div>
            </div>
          </div>


          <div class="layui-row modal_footer">
            <button type="button" class="layui-btn layui-btn-normal" id="submit">
              确认提交
            </button>
            <button type="button" class="layui-btn layui-btn-primary" id="closeLayer">取消</button>
          </div>
        </form>
      </div>
    </div>
  </div>
  <script src="../../layuiadmin/layui/layui.all.js"></script>
  <script src="../utils.js"></script>
  <script src="../jquery-1.10.2.js"></script>
  <script type="text/javascript" src="../../cropper/cropper.js"></script>
  <script>
    closeLayer();// 关闭当前弹窗
    // var val = GetQueryString("val");
    var fileName = decodeURI(GetQueryString("fileName"));
    // var fileName = JSON.parse(window.sessionStorage.getItem('fileData')).name;
    var val = window.sessionStorage.getItem('coverImage');

    document.querySelector('#cropImg').src = val;

    $('#cropImg').cropper({
      aspectRatio: 1 / 1,
      viewMode: 1,
      // modal: false,//黑色模态
      minContainerWidth: 500,   //容器最小的宽度
      minContainerHeight: 500,  //容器最小的高度
      dragMode: 'move',         //设置裁剪框为可以移动
      preview: [document.querySelector('.previewBox')],//预览
      crop: function (e) {
        // console.log(e);
      }
    });


    $("#submit").on("click", function () {
      // console.log($('#cropImg').cropper('getCroppedCanvas'));
      var cas = $('#cropImg').cropper('getCroppedCanvas', {
        width: 160,
        height: 90,
        minWidth: 256,
        minHeight: 256,
        maxWidth: 4096,
        maxHeight: 4096,
        fillColor: '#fff',
        imageSmoothingEnabled: false,
        imageSmoothingQuality: 'high',
      });
      //  上传
      cas.toBlob(function (blob) {
        console.log('生成Blob的图片格式', blob);  //生成Blob的图片格式
        // 裁剪后的 blob 地址
        console.log(URL.createObjectURL(blob));

        var formData = new FormData()
        var fileOfBlob = new File([blob], fileName);
        // console.log('fileOfBlob', fileOfBlob);
        formData.append("file", fileOfBlob);
        // console.log('formData', formData);
        var loadIcon1 = layer.load(2);
        $.ajax({
          url: contextPath + '/AliOssUpload',
          type: "POST",
          data: formData,
          cache: false,
          processData: false,
          contentType: false,//避免 JQuery 对其操作,从而失去分界符,而使服务器不能正常解析文件
          success: function (res) {
            layer.close(loadIcon1);
            if (res.rt == 0) {
              let url = res.data
              coverImageUrl = url;
              let a = parent.setImg(url);//注意这里调用父层的JS 实现传值
              var index = parent.layer.getFrameIndex(window.name);//获取当前层
              parent.layer.close(index);//关闭当前层
              return false;
            } else if (res.rt == -1) {
              //错误信息
              layer.open({
                title: '错误信息',
                icon: 2,
                content: res.msg
              });
            }
          }
        });
      })
    })



 
  </script>
</body>

</html>

你可能感兴趣的:(前端,js,前端,javascript,layui)