JCrop与ajaxfileupload整合的用法(java版本)

来源:互联网 发布:2017程序员就业现状 编辑:程序博客网 时间:2024/04/28 16:54

JCrop官方下载地址:http://deepliquid.com/content/Jcrop.html


前两天项目中需要用到上传头像的功能,偶然找到了jcrop,虽然是一款javascript插件,但是显示效果堪比flash。

与ajaxfileupload整合后特别好用。


下面是源码:

1、引用代码区:

<link href="css/jquery.Jcrop.min.css" type="text/css"  rel="stylesheet" />
<script src="js/jquery-1.6.4.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/axfileupload.js"></script>
<script type="text/javascript" src="js/Jcrop/jquery.color.js"></script>
<script type="text/javascript" src="js/Jcrop/jquery.Jcrop.min.js"></script>

2、页面:

<div class="face_right">
                                <div class="upload">
                                    <form action="cut_face" method="post">
                                        <div>
                                            <p style="font-size: 15px">
                                                设置新头像
                                            </p>
                                            <p>
                                                1.使用真实照片,展示自我风采,可以在大照片中裁剪满意的部分。
                                            </p>
                                            <p>
                                                2.支持jpg、gif、png和bmp格式图片。
                                            </p>
                                            <p>
                                                3.最大支持10M图片。
                                            </p>
                                        </div>
                                        <div class="picture">
                                            <input type="file" id="fn"
                                                style="opacity: 0; width: 70px; position: absolute; filter: alpha(opacity =   0);"
                                                onchange="select_img();" />
                                            <a class="btnl" style="color: #FFFFFF; cursor: pointer;">选择图片</a>
                                        </div>
                                        <div class="background" id="back_ground">

                                        </div>

                                        <input type="hidden" id="image_name" name="image_name" />

                                        <input type="hidden" id="x" name="x" value="" /><!--四个值分别用来存储截取的四个位置-->
                                        <input type="hidden" id="y" name="y" value="" />
                                        <input type="hidden" id="x2" name="x2" value="" />
                                        <input type="hidden" id="y2" name="y2" value="" />
                                        <div class="upload_button">
                                            <input type="submit"
                                                style="display: none; padding: 3px; cursor: pointer;"
                                                class="btnl" value="保存" />
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>

3、js代码:

                <script>


function select_img() {
    var value = $("#fn").val();
    var ext = value.substring(value.lastIndexOf(".") + 1).toLowerCase();
    if (ext == null
            || ext == ""
            || (ext != "jpg" && ext != "gif" && ext != "bmp" && ext != "jpeg" && ext != "png")) {
        art.dialog( {
            title : '提示',
            icon : 'error',
            content : '不支持的照片格式'
        }).lock().time(3);
        return;
    }
    $("#back_ground").html(
            "<img src='<%=img%>loading.gif' style='margin-top:100px;'/>");
    $.ajaxFileUpload( {
        url : "upload_user_head",
        secureuri : false,
        dataType : 'json',
        type : "post",
        fileElementId : "fn",
        success : function(data, status) {
            $("#back_ground")
                    .html(
                            "<img id='target' src='<%=facePath%>1/" + data.img
                                    + "' />").css( {
                        "background" : "#FFFFFF"
                    });
            $("#image_name").val(data.img);
            $(".btnl").show();
            adjustwh();
            do_Jcrop();
        }
    })
}

function adjustwh() {
    var image = new Image();
    image.src = $("#target").attr('src');
    var true_width = image.width;
    var true_height = image.height;
    if (true_width / true_height > 16 / 9) {
        $("#target").css( {
            "width" : "400"
        });
        $("#zoom_rate").val(400 / true_width);
    } else {
        $("#target").css( {
            "height" : "249"
        });
        $("#zoom_rate").val(249 / true_height);
    }
}

function do_Jcrop() {
    var api;
    $('#target').Jcrop( {
        // start off with jcrop-light class
        bgOpacity : 0.5,
        bgColor : 'white',
        aspectRatio : 1,
        addClass : 'jcrop-light',
        onChange : showCoords,
        onSelect : showCoords
    }, function() {
        api = this;
        api.setSelect( [ 130, 65, 130 + 350, 65 + 285 ]);
        api.setOptions( {
            bgFade : true
        });
        api.ui.selection.addClass('jcrop-selection');
    });

    $('#buttonbar')
            .on(
                    'click',
                    'button',
                    function(e) {
                        var $t = $(this), $g = $t.closest('.btn-group');
                        $g.find('button.active').removeClass('active');
                        $t.addClass('active');
                        $g
                                .find('[data-setclass]')
                                .each(
                                        function() {
                                            var $th = $(this), c = $th
                                                    .data('setclass'), a = $th
                                                    .hasClass('active');
                                            if (a) {
                                                api.ui.holder.addClass(c);
                                                switch (c) {

                                                case 'jcrop-light':
                                                    api.setOptions( {
                                                        bgColor : 'white',
                                                        bgOpacity : 0.5
                                                    });
                                                    break;

                                                case 'jcrop-dark':
                                                    api.setOptions( {
                                                        bgColor : 'black',
                                                        bgOpacity : 0.4
                                                    });
                                                    break;

                                                case 'jcrop-normal':
                                                    api
                                                            .setOptions( {
                                                                bgColor : $.Jcrop.defaults.bgColor,
                                                                bgOpacity : $.Jcrop.defaults.bgOpacity
                                                            });
                                                    break;
                                                }
                                            } else
                                                api.ui.holder.removeClass(c);
                                        });
                    });

}
function showCoords(c) {
    jQuery('#x').val(c.x);
    jQuery('#y').val(c.y);
    jQuery('#x2').val(c.x2);
    jQuery('#y2').val(c.y2);
};

</script>

5、后台两段代码:

@RequestMapping(value="upload_user_head")
    public void uploadUserHead(MultipartHttpServletRequest multipartRequest,HttpSession session,HttpServletRequest request,ModelMap map,HttpServletResponse response) throws IOException{
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/plain");
        PrintWriter  out =  response.getWriter();
        MultipartFile file  =  multipartRequest.getFile("fn");  
            if (file == null) {    
                out.write("0");   
            }else{    
                if(file.getSize()>10000000)         
                {    
                    out.write("1");              
                }else if(file.getSize()>0){         
                       String filename=file.getOriginalFilename();
                       String imgUrl= SaveFileFromInputStream(file.getInputStream(),filename,request,0);
                       out.write("{\"img\":\""+imgUrl+"\"}");
                }    
            }
            out.flush();   
             out.close();
    }
    
    @RequestMapping(value="/cut_face")
    public String cut_face(HttpServletRequest request,ModelMap map,HttpServletResponse response,HttpSession session){
        TbUser user = (TbUser) session.getAttribute("user");
        try{
        String image_name = request.getParameter("image_name");
        int x = Integer.parseInt(request.getParameter("x"));
        int y = Integer.parseInt(request.getParameter("y"));
        int x2 = Integer.parseInt(request.getParameter("x2"));
        int y2 = Integer.parseInt(request.getParameter("y2"));
//        System.out.println(x+","+y+","+x2+","+y2+","+","+image_name);
        ImageCutUtil.cutImageByXY(FileStorage.getDocumentItemStorage(request)+separator+"1"+separator+image_name,
                FileStorage.getDocumentItemStorage(request)+separator+"0"+separator+image_name,
                x, y, x2,y2, 120, 120);
        user.setHeadurl(image_name);
        userDao.attachDirty(user);
        }catch(Exception e){
            
        }
        
        return "redirect:/my_face";
    }
   

原创粉丝点击