莫辂技术
今天是:
我需要三件东西:爱情友谊和图书。然而这三者之间何其相通!炽热的爱情可以充实图书的内容,图书又是人们最忠实的朋友。
User Image Jcrop使用 2018-11-30

1.github地址 https://github.com/tapmodo/Jcrop

2. 插件地址:http://deepliquid.com/content/Jcrop.html因想实现一个头像修改的功能,通过网上搜索,觉得Jcrop不错。先来看一下简单的实现效果

3.实现步骤

引入js和css文件

<script src="${ctx}/js/jcrop/jquery.Jcrop.min.js"></script>
<link rel="stylesheet" href="${ctx}/css/jcrop/jquery.Jcrop.min.css">
<style type="text/css">
  .jcrop-holder #preview-pane {
    display: block;
    position: absolute;
    z-index: 2000;
    padding: 2px;;
    right: -20%;
    border: 1px rgba(0,0,0,.4) solid;
    background-color: white;

    -webkit-border-radius: 6px;
    -moz-border-radius: 6px;
    border-radius: 6px;

    -webkit-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
    -moz-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
    box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
  }

  #preview-pane .preview-container {
    width: 100px;
    height: 100px;
    overflow: hidden;
  }

</style>

HTML

<div class="active tab-pane"  id="activity">
  <form id="imageInfo">
    <div class="row">
      <div class="col-md-9">
        <img style="width: 100%;" src="${ctx}/common/showImg?path=${ctx}/images/profile/admin/admin_origin.jpg" id="profile">
        <input type="hidden" id="origin" name="origin" value="/images/profile/admin/admin_origin.jpg"/>
        <input type="hidden" id="x" name="x" />
        <input type="hidden" id="y" name="y" />
        <input type="hidden" id="w" name="w" />
        <input type="hidden" id="h" name="h" />
        <input type="hidden" id="boundx" name="boundx" >
        <input type="hidden" id="boundy" name="boundy" >
      </div>
      <div class="col-sm-3">
            <div id="preview-pane">
              <div class="preview-container">
                <img src="${ctx}/common/showImg?path=${ctx}/images/profile/admin/admin_origin.jpg" alt="Preview" />
              </div>
            </div>
      <%--                        <strong>头像预览</strong>
            <div id="preview1">
            <img id="preview100" class="img-circle" style="margin: 10px 10px; width: 100px;height: 100px;" src="${ctx}/common/showImg?path=${ctx}/images/profile/admin/admin_origin.jpg">
            <p class="text-muted text-left">大头像100x100</p>
            </div>
            <img id="preview45" class="img-circle" style="margin: 10px 10px; width: 45px;height: 45px;" src="${ctx}/common/showImg?path=${ctx}/images/profile/admin/admin_origin.jpg">
            <p class="text-muted text-left">小头像45x45</p>--%>

          <!-- /.box-body -->
      </div>
    </div>
    <div class="row">
      <div class="col-sm-3">
      <button type="button" class="btn btn-block btn-success btn-sm right" style="margin-top: 10px" onclick="saveCutImage();">确认修改</button>
      </div>
    </div>
  </form>
</div>

JS

<script>
    jQuery(function($){

        // Create variables (in this scope) to hold the API and image size
        var jcrop_api,
            boundx,
            boundy,
            // Grab some information about the preview pane
            $preview = $('#preview-pane'),
            $pcnt = $('#preview-pane .preview-container'),
            $pimg = $('#preview-pane .preview-container img'),
            xsize = $pcnt.width(),
            ysize = $pcnt.height();

        console.log('init',[xsize,ysize]);
        $('#profile').Jcrop({
            onChange: updatePreview,
            onSelect: updatePreview,
            aspectRatio: xsize / ysize
        },function(){
            // Use the API to get the real image size
            var bounds = this.getBounds();
            boundx = bounds[0];
            boundy = bounds[1];
            // Store the API in the jcrop_api variable
            jcrop_api = this;

            // Move the preview into the jcrop container for css positioning
            $preview.appendTo(jcrop_api.ui.holder);
        });

        function updatePreview(c) {
            debugger;
            $("#boundx").val(boundx);
            $("#boundy").val(boundy);
            $("#x").val(c.x);
            $("#y").val(c.y);
            $("#w").val(c.w);
            $("#h").val(c.h);
            if (parseInt(c.w) > 0)
            {
                var rx = xsize / c.w;
                var ry = ysize / c.h;

                $pimg.css({
                    width: Math.round(rx * boundx) + 'px',
                    height: Math.round(ry * boundy) + 'px',
                    marginLeft: '-' + Math.round(rx * c.x) + 'px',
                    marginTop: '-' + Math.round(ry * c.y) + 'px'
                });
            }
        };

    });
        function  uploadFile(){
        var formData = new FormData($("#uploadForm")[0]);
        $.ajax({
            url:"${ctx}/sysUser/saveUserPhoto?user="+$("#username").val(),
            type:"POST",
            data:formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success:function (res) {
                debugger;
                $("#profile").attr("src","${ctx}/common/showImg?path="+res.filePath);
            }
        });
    }
    function saveCutImage(){
            debugger;
        $.ajax({
            url:"${ctx}/sysUser/saveCutImage",
            dataType:"JSON",
            data:$("#imageInfo").serialize(),
            type:"post",
            success:function (res,status) {
                alert(res.msg);
                getContent('${ctx}//sysUser/userProfile');
            }
        });
    }
</script>

后台处理

@RequestMapping(value = "saveCutImage")
@ResponseBody
public Map<String,Object> saveCutImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Map<String, Object> result = new HashMap<String, Object>();
    int x = Integer.valueOf(request.getParameter("x"));
    int y = Integer.valueOf(request.getParameter("y"));
    int w = Integer.valueOf(request.getParameter("w"));
    int h = Integer.valueOf(request.getParameter("h"));
    int boundx = Integer.valueOf(request.getParameter("boundx"));
    int boundy = Integer.valueOf(request.getParameter("boundy"));
    String origin = request.getParameter("origin");
    String userName=SpringSecurityContextUtil.getUserDetails().getUsername();
    String cutImagePath=Constants.PROJECT_PATH+Constants.UPLOAD_USER_PATH+userName+File.separator+userName+"_100x100.jpg";
    CutImage.cutImage(origin,cutImagePath,x,y,w,h,boundx,boundy);
    SysUser sysUser= (SysUser) sysUserService.getUserByUsername(userName);
    sysUser.setImageurl(Constants.UPLOAD_USER_PATH+userName+File.separator+userName+"_100x100.jpg");
    sysUserService.updateByPrimaryKey(sysUser);

    HttpSession session = request.getSession();

    //首先将原session中的数据转移至一临时map中
    Map<String,Object> tempMap = new HashMap();
    Enumeration<String> sessionNames = session.getAttributeNames();
    while(sessionNames.hasMoreElements()){
        String sessionName = sessionNames.nextElement();
        tempMap.put(sessionName, session.getAttribute(sessionName));
    }

    //注销原session,为的是重置sessionId
    session.invalidate();

    //将临时map中的数据转移至新session
    session = request.getSession();
    //将修改后的用户保存到session中
    session.setAttribute("currUser", sysUser);
    for(Map.Entry<String, Object> entry : tempMap.entrySet()){
        session.setAttribute(entry.getKey(), entry.getValue());
    }
    result.put("msg","头像设置成功");
    return result;
}
45 likes - 2 comments

我的

类型标签

外部链接

网站访问总量