欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用Jcrop插件裁剪图片并上传(Spring MVC)

程序员文章站 2022-04-09 09:15:48
...

Jcrop的使用详见:http://code.ciaoca.com/jquery/jcrop/

页面代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>图片裁剪上传</title>
<link rel="stylesheet" href="${pageContext.request.contextPath}/static/css/jquery.Jcrop.min.css"/>
<style>
    .jcrop-holder{
        float:left;
    }
    .pre-wrapper{
        display:none;
        float:left;
        margin-left:50px;

        padding: 6px;
        border: 1px rgba(0,0,0,.4) solid;
        background-color: white;

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

        -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);
    }
    .btn-wrapper{clear:both;}
    #upload-btn{display:none;}
</style>
<script type="application/javascript" src="${pageContext.request.contextPath}/static/js/jquery-3.2.1.min.js"></script>
<script type="application/javascript" src="${pageContext.request.contextPath}/static/js/jquery.Jcrop.min.js"></script>
</head>
<body>

<label for="src-input">选择图片:</label><input id="src-input" type="file"/>
<div class="img-wrapper"><img id="img-show" src=" "/></div>
<div class="pre-wrapper"><canvas class="pre-show" width="200px" height="200px"></canvas></div>
<div class="btn-wrapper"><button id="upload-btn">上传裁剪图片</button></div>
<script>
    var jcropApi;
    var srcImg = $("#img-show")[0];
    var srcInput = $("#src-input");
    $("#img-show").Jcrop({
        allowSelect: true,
        allowMove: true,
        allowResize: true,
        baseClass: 'jcrop',
        bgColor: 'black',
        bgOpacity: 0.6,
        bgFade: true,
        aspectRatio: 1,
        borderOpacity: 0.4,
        drawBorders: true,
        dragEdges: true,
        boxWidth: 400,
        fadeTime: 400,
        animationDelay: 20,
        swingSpeed: 3,
        onChange: getPosition
    },function(){
        jcropApi = this;    
    });
    srcInput.change(function(){
        if(!this.files[0].name.match(/.jpg|.gif|.png|.bmp/i)){
            alert("你选择的文件类型不被支持!");
            return ;
        }
        var reader=new FileReader();
        reader.readAsDataURL(this.files[0]);
        reader.onload=function(){
            srcImg.src = this.result;
            jcropApi.setImage(this.result);
            reader=null;
        };
    });

    function getPosition(p){
        preShow(p.x,p.y,p.w,p.h);
    }

    var canvas = $(".pre-show")[0];
    var cxt = canvas.getContext("2d");
    function preShow(x,y,w,h){
        $(".pre-wrapper").show();
        $("#upload-btn").show();

        var img=new Image();
        img.onload = function () {
            cxt.drawImage(img,x,y,w,h,0,0,200,200);
        };
        img.src=srcImg.src;
    }

    $("#upload-btn").click(function(){
        var src=canvas.toDataURL("image/jpeg");
        $.ajax({
            url:"upload",
            type:"POST",
            data:{img:src},
            dataType:"json",
            success:function(data){
                alert("上传成功!文件名:"+data);
            }
        });
    }); 
</script>
</body>
</html>

后台Controller

@Controller
public class UploadController {

    @PostMapping("upload")
    @ResponseBody
    public String upload(HttpServletRequest request,String img) {
        String serverPath = request.getSession().getServletContext()  
                .getRealPath("/");  
        Base64 base64 = new Base64();  
        try {  
            //实际的图片数据是从 data:image/jpeg;base64, 后开始的  
            byte[] k = base64.decode(img.substring("data:image/jpeg;base64,"  
                    .length()));  
            InputStream is = new ByteArrayInputStream(k);  
            String fileName = UUID.randomUUID().toString();  
            String imgFilePath = serverPath + "\\usertemp\\" + fileName + ".jpg";  

            BufferedImage image = ImageIO.read(is);   
            ImageIO.write(image, "jpg", new File(imgFilePath));  
            return fileName;  
        } catch (Exception e) {  
            e.printStackTrace();
            return "error";  
        }  
    }
}

Spring MVC配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="false">
             <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">  
                <property name="supportedMediaTypes">  
                    <list>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>  
                    </list>  
                </property>  
            </bean>  
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!-- 扫描生成controller组件 -->
    <context:component-scan base-package="controller"/>

    <!-- 静态资源 -->
    <mvc:resources location="/static/" mapping="/static/**"/>

    <!-- 配置根视图 -->
    <mvc:view-controller path="/" view-name="index"/>
    <mvc:view-controller path="/index2" view-name="index2"/>

    <!-- 默认的视图解析器- -->
    <bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="contentType" value="text/html"/>
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>


</beans>