jcrop截图并上传服务器 + java

我使用的截图插件是Jcrop,插件地址 http://code.ciaoca.com/jquery/jcrop

先上代码

<head>
    <script type="text/javascript" src="../images/jcrop/js/jquery-1.12.4.min.js"></script>
    <script type="text/javascript" src="../images/jcrop/js/jquery.Jcrop.min.js"></script>
    <script type="text/javascript" src="../images/jcrop/js/script.js"></script>
    <link  rel="stylesheet" href="../images/jcrop/css/jquery.Jcrop.min.css">   
    <link  rel="stylesheet" href="../images/jcrop/css/common.css">
</head>
<body>
     <div class="container">
        <div class="demo" style="margin-top:20px;">
            <form id="upload_form" enctype="multipart/form-data" method="post" action="cutImageAndImport" onsubmit="return checkForm()" target="fileName_iframe">
                <!-- hidden crop params -->
                <input type="hidden" id="x" name="x" autocomplete="off">
                <input type="hidden" id="y" name="y" autocomplete="off">
                <input type="hidden" id="w" name="w" autocomplete="off">
                <input type="hidden" id="h" name="h" autocomplete="off">
                <a href="javascript:;" class="a-upload">选择图片<input type="file" name="image_file" id="image_file" onchange="fileSelectHandler()" accept="images/*"></a>
                <input type="hidden" id="partyheadUrl" name="partyheadUrl" autocomplete="off">
                <div class="error">注意:上传前,先截图</div>
                <div class="step2">
                    <div style="float:left;margin-right:20px;">
            <!--初始化的时候放一张默认图片-->
<img id="preview" src="../images/uploadImage.png" style="width:200px;height:200px;" > </div>
            <!--这个地方展示被截取的图片--> <div id="preview_box" style="width:200px;height:200px;overflow: hidden;"> <img id="crop_preview" src=""> </div> </div> <div style="margin-top:20px;"> <input id="upload" type="submit" value="上传" class="btn"> <!--<input id="confirmbtn" type="button" style="visibility:hidden;" value="确定" class="btn">--> <input id="cancelbtn" type="button" value="取消" class="btn" style="background-color:#f2f2f5;color:#333;"> </div> </form> </div> </div> </body> </html> <iframe name="fileName_iframe" style="display:none"></iframe>

 js代码,这块的代码也是参考了网上发布的代码

// check for selected crop region
function checkForm() {
    if (parseInt($('#w').val()))
        return true;
    $('.error').html('请先选择图片,并且截图').show();
    return false;
}

// update info by cropping (onChange and onSelect events handler)

var oImage = undefined;
var blob = undefined;
var jcrop_api = undefined;     
function updateInfo(e) {
    /*$('#x').val(e.x);
    $('#y').val(e.y);
    $('#x2').val(e.x2);
    $('#y2').val(e.y2);
    $('#w').val(e.w);
    $('#h').val(e.h);*/
    if(parseInt(e.w) > 0){
        //计算预览区域图片缩放的比例,通过计算显示区域的宽度(与高度)与剪裁的宽度(与高度)之比得到
        var rx = $("#preview_box").width() / e.w; 
        var ry = $("#preview_box").height() / e.h;
        //通过比例值控制图片的样式与显示
        $("#crop_preview").css({
            width:Math.round(rx * $("#preview").width()) + "px",    //预览图片宽度为计算比例值与原图片宽度的乘积
            height:Math.round(rx * $("#preview").height()) + "px",  //预览图片高度为计算比例值与原图片高度的乘积
            marginLeft:"-" + Math.round(rx * e.x) + "px",
            marginTop:"-" + Math.round(ry * e.y) + "px"
        });
        
       // var canvas=$('#previewCanvas')[0];
        //展示长度与实际长度的比例
        var xp = e.x/$("#preview").width();
        var yp = e.y/$("#preview").height();
        //var canvas = $('<canvas width="'+Math.round(oImage.width/rx)+'" height="'+Math.round(oImage.height/ry)+'"></canvas>')[0],
        /*$('#previewCanvas').css({
            width:Math.round(oImage.width/rx) + "px",
            height:Math.round(oImage.height/ry) + "px"
        });*/
        //通过比例来计算实际图片所需截取的尺寸
        $('#x').val(Math.round(oImage.width*xp));
        $('#y').val(Math.round(oImage.height*yp));
        $('#w').val(Math.round(oImage.width/rx));
        $('#h').val(Math.round(oImage.height/ry));
        //被注释掉的代码是用canvas画图的,不过我这里接下的涂油一点问题所以没有采用,如果又能解决的话一定要通知我
       /* ctx=canvas.getContext('2d');

        ctx.drawImage(oImage,Math.round(oImage.width*xp),Math.round(oImage.height*yp),Math.round(oImage.width/rx),Math.round(oImage.height/ry),0,0,Math.round(oImage.width/rx),Math.round(oImage.height/ry));
        //console.trace(ctx);
        //ctx.drawImage(oImage,Math.round(oImage.width*xp),Math.round(oImage.height*yp),1000,1000,0,0,1000,1000);
        var data=canvas.toDataURL();
        // dataURL 的格式为 “data:image/png;base64,****”,逗号之前都是一些说明性的文字,我们只需要逗号之后的就行了
        data=data.split(',')[1];
        data=window.atob(data);
        var ia = new Uint8Array(data.length);
        for (var i = 0; i < data.length; i++) {
            ia[i] = data.charCodeAt(i);
        };

        // canvas.toDataURL 返回的默认格式就是 image/png
        blob=new Blob([ia], {type:"image/png"});*/
        //$(document.body).append(canvas);
    }
};

// clear info by cropping (onRelease event handler)
function clearInfo() {
    $('.info #w').val('');
    $('.info #h').val('');
}
function fileSelectHandler() {
    
    //清空原有图片路径
    $("#partyheadUrl").val("");// get selected file
    var oFile = $('#image_file')[0].files[0];

    // hide all errors
    $('.error').hide();

    // check for image type (jpg and png are allowed)
    var rFilter = /^(image\/jpeg|image\/png|image\/jpg)$/i;
    if (!rFilter.test(oFile.type)) {
        $('.error').html('请选择jpg、jpeg或png格式的图片').show();
        return;
    }

    // check for file size
    /*if (oFile.size > 1000 * 1024) {
        $('.error').html('请上传小于1M的图片').show();
        return;
    }*/

    // preview element
    oImage = document.getElementById('preview');

    var crop_preview = document.getElementById('crop_preview');
    // prepare HTML5 FileReader
    var oReader = new FileReader();
    oReader.onload = function(e) {
          // destroy Jcrop if it is existed在上传文件变化时一定要销毁jcrop_api否则$("#preview")展示图片不会变
        if (typeof jcrop_api != 'undefined')
            jcrop_api.destroy();
        // e.target.result contains the DataURL which we can use as a source of the image
        oImage.src = e.target.result; 
        crop_preview.src = e.target.result;
               
        oImage.onload = function() { // onload event handler

            // display step 2
            $('.step2').fadeIn(500);

            // display some basic image info
            var sResultFileSize = bytesToSize(oFile.size);
            $('#filesize').val(sResultFileSize);
            $('#filetype').val(oFile.type);
            $('#filedim').val(oImage.naturalWidth + ' x ' + oImage.naturalHeight);

            // Create variables (in this scope) to hold the Jcrop API and image size
            var boundx, boundy;

            // initialize Jcrop
            $('#preview').Jcrop({
                minSize: [32, 32], // min crop size
                aspectRatio: 1, // keep aspect ratio 1:1
                bgFade: true, // use fade effect
                bgOpacity: .3, // fade opacity
                onChange: updateInfo,
                onSelect: updateInfo,
                onRelease: clearInfo
            }, 
            function() {
                // use the Jcrop API to get the real image size
                var bounds = this.getBounds();
                boundx = bounds[0];
                boundy = bounds[1];

                // Store the Jcrop API in the jcrop_api variable
                jcrop_api = this;
                jcrop_api.setSelect([50,50,150,150]);
            });
        };
    };

    // read selected file as DataURL
    oReader.readAsDataURL(oFile);
}

//后台返回图片地址
function fileImport_callBack(filePath){    parent.$("#partyheadUrl").val(filePath);
    parent.$("#logoPhoto").attr("src",filePath);
    closeDialog("dialog");
}

 后台处理代码

/**
     * 上传截图图片
     * @param request
     * @param response
     * @return
     */
    public static String cutImageAndImport(HttpServletRequest request, HttpServletResponse response)
    {
     //从前台传来需要截取的尺寸 String left
= (String)request.getParameter("x"); String top = (String)request.getParameter("y"); String width = (String) request.getParameter("w"); String height = (String) request.getParameter("h"); String callBack = ""; String result = ModelService.RESPOND_ERROR; String returnFilePath = ""; Map<String, Object> jsonMap = FastMap.newInstance(); try { Map<String, Object> paramMap = FastMap.newInstance(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = UtilGenerics.<FileItem> checkList(upload.parseRequest(request)); Iterator<FileItem> it = items.iterator(); while (it.hasNext()) { FileItem item = it.next(); if (item.isFormField()){ String fieldName = item.getFieldName(); Object fieldValue = item.getString("UTF-8"); if("x".equals(fieldName)&&UtilValidate.isEmpty(left)){ left = (String) fieldValue; }else if("y".equals(fieldName)&&UtilValidate.isEmpty(top)){ top = (String) fieldValue; }else if("w".equals(fieldName)&&UtilValidate.isEmpty(width)){ width = (String) fieldValue; }else if("h".equals(fieldName)&&UtilValidate.isEmpty(height)){ height = (String) fieldValue; } if (!paramMap.containsKey(fieldName)) { paramMap.put(fieldName, fieldValue); } else if (paramMap.containsKey(fieldName)) { Object mapValue = paramMap.get(fieldName); if (mapValue instanceof List<?>) { checkList(mapValue, Object.class).add(fieldValue); } else if (mapValue instanceof String) { List<String> newList = FastList.newInstance(); newList.add((String) mapValue); newList.add((String) fieldValue); paramMap.put(fieldName, newList); } else { Debug.logWarning("Form field found [" + fieldName + "] which was not handled!", module); } } } else{ if (item.getSize() > 0){ InputStream input = item.getInputStream(); // ImageIO 支持的图片类型 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif] String types = Arrays.toString(ImageIO.getReaderFormatNames()).replace("]", ","); String suffix = null; // 获取图片后缀 if(item.getName().indexOf(".") > -1) { suffix = item.getName().substring(item.getName().lastIndexOf(".") + 1); }// 类型和图片后缀全部小写,然后判断后缀是否合法 if(suffix == null || types.toLowerCase().indexOf(suffix.toLowerCase()+",") < 0){ jsonMap.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR); jsonMap.put(ModelService.ERROR_MESSAGE,"Sorry, the image suffix is illegal. the standard image suffix is {}." + types); return null; } // 将InputStream 转换为ImageInputStream ImageInputStream iis = null; iis = ImageIO.createImageInputStream(input); // 根据图片类型获取该种类型的ImageReader ImageReader reader = ImageIO.getImageReadersBySuffix(suffix).next(); reader.setInput(iis,true); ImageReadParam param = reader.getDefaultReadParam(); //设置截取参数 Rectangle rect = new Rectangle(Integer.valueOf(left), Integer.valueOf(top), Integer.valueOf(width), Integer.valueOf(height)); param.setSourceRegion(rect); BufferedImage bi = reader.read(0, param); ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); ImageIO.write(bi, suffix, swapStream); ByteBuffer uploadedFile = ByteBuffer.wrap(swapStream.toByteArray()); Map resultMap = 在这里调用上传服务器的服务,我们是存储在阿里云,就不便贴出; returnFilePath = imageFolder+(String) resultMap.get("filePath"); } } } jsonMap.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS); jsonMap.put("returnFilePath", returnFilePath); result = ModelService.RESPOND_SUCCESS; } catch (Exception e) { callBack="<script>alert('上传失败')</script>"; //jsonMap.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR); Debug.logError(e, e.getLocalizedMessage(), module); } callBack="<script>parent.fileImport_callBack('"+returnFilePath+"')</script>"; PrintWriterUtil.print(response, callBack); //JsonUtil.toJsonObject(jsonMap,response); return result; }

 

posted on 2016-07-12 22:04  会飞的小强  阅读(839)  评论(0)    收藏  举报

导航