springMVC结合Jcrop实现头像上传裁剪预览功能--javaweb修订版

来源:互联网 发布:证券交易软件下载 编辑:程序博客网 时间:2024/05/22 06:44
原文地址:http://my.oschina.net/zhengweishan/blog/700677

 

先说下基本的环境:maven+springmvc+jcrop

一言不合就放源码:http://git.oschina.net/zhengweishan/springmvc-jcrop (完全可以跑起来的项目,直接就可以看见效果)。

下面在浪费下空间,如果不想下载源码看,就看这里吧:往下看,往下看,往下看,在往下看。

Pom.xml文件:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">    <modelVersion>4.0.0</modelVersion>    <groupId>com.springjcrop.demo</groupId>    <artifactId>spring-jcrop</artifactId>    <packaging>war</packaging>    <version>0.0.1-SNAPSHOT</version>    <name>spring-jcrop Maven Webapp</name>    <url>http://maven.apache.org</url>    <properties>        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>        <org.springframework.version>4.2.5.RELEASE</org.springframework.version>    </properties>    <dependencies>        <dependency>            <groupId>junit</groupId>            <artifactId>junit</artifactId>            <version>3.8.1</version>            <scope>test</scope>        </dependency>        <!-- servlet -->        <dependency>            <groupId>javax.servlet</groupId>            <artifactId>javax.servlet-api</artifactId>            <version>3.1.0</version>        </dependency>        <!-- jstl -->        <dependency>            <groupId>javax.servlet</groupId>            <artifactId>jstl</artifactId>            <version>1.2</version>        </dependency>        <!-- fileupload -->        <dependency>            <groupId>commons-fileupload</groupId>            <artifactId>commons-fileupload</artifactId>            <version>1.3</version>        </dependency>        <!-- spring -->        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-context</artifactId>            <version>${org.springframework.version}</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-context-support</artifactId>            <version>${org.springframework.version}</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-web</artifactId>            <version>${org.springframework.version}</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-webmvc</artifactId>            <version>${org.springframework.version}</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-jdbc</artifactId>            <version>${org.springframework.version}</version>        </dependency>    </dependencies>    <build>        <finalName>spring-jcrop</finalName>    </build></project>

Web.xml文件:

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"><web-app>    <context-param>        <param-name>contextConfigLocation</param-name>        <param-value>            classpath*:servlet-context.xml        </param-value>    </context-param>    <listener>        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener>    <servlet>        <servlet-name>appServlet</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <init-param>            <param-name>contextConfigLocation</param-name>            <param-value>classpath*:servlet-context.xml</param-value>        </init-param>        <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>        <servlet-name>appServlet</servlet-name>        <url-pattern>/</url-pattern>    </servlet-mapping></web-app>

Servlet-context.xml:

<span style="font-size:12px;"><?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"    xmlns:task="http://www.springframework.org/schema/task" xmlns:mvc="http://www.springframework.org/schema/mvc"    xmlns:tx="http://www.springframework.org/schema/tx"    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd     http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd      http://www.springframework.org/schema/mvc      http://www.springframework.org/schema/mvc/spring-mvc.xsd      http://www.springframework.org/schema/tx      http://www.springframework.org/schema/tx/spring-tx.xsd"    default-lazy-init="false">    <mvc:annotation-driven>        <!-- 消息转换器 -->        <mvc:message-converters register-defaults="true">            <bean class="org.springframework.http.converter.StringHttpMessageConverter">                <property name="supportedMediaTypes" value="text/html;charset=UTF-8" />            </bean>        </mvc:message-converters>    </mvc:annotation-driven>    <!-- 静态资源 -->    <mvc:resources mapping="/resources/**" location="/resources/" />    <!-- 中文乱码解决 -->    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">        <property name="messageConverters">            <list>                <bean                    class="org.springframework.http.converter.StringHttpMessageConverter">                    <property name="supportedMediaTypes">                        <list>                            <value>text/plain;charset=UTF-8</value>                        </list>                    </property>                </bean>            </list>        </property>    </bean>    <!-- 文件解析器 -->    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />    <!-- 视图解析器 -->    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">        <!-- 前缀 -->        <property name="prefix" value="/" />        <!-- 后缀 -->        <property name="suffix" value=".jsp" />    </bean>    <!-- 自动扫描包 -->    <context:component-scan base-package="com.springjcrop.demo" /></beans></span>

两个工具类:

文件上传工具类:

package com.springjcrop.demo;import java.util.Arrays;import java.util.Date;import java.util.List;import java.util.Random;public class FileUploadUtil {     public static final List<String> ALLOW_TYPES = Arrays.asList(                "image/jpg","image/jpeg","image/png","image/gif"        );    //文件重命名        public static String rename(String fileName){            int i = fileName.lastIndexOf(".");            String str = fileName.substring(i);            return new Date().getTime()+""+ new Random().nextInt(99999999) +str;        }    //校验文件类型是否是被允许的        public static boolean allowUpload(String postfix){            return ALLOW_TYPES.contains(postfix);        }} 
Controller:

package com.springjcrop.demo;import java.io.File;import javax.servlet.http.HttpServletRequest;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.multipart.MultipartFile;@Controller @RequestMapping("/UploadDemo")public class UploadImgController {        @RequestMapping(value = "/uploadHeadImage",method = RequestMethod.POST)    public String uploadHeadImage(            HttpServletRequest request,            @RequestParam(value = "x") String x,            @RequestParam(value = "y") String y,            @RequestParam(value = "h") String h,            @RequestParam(value = "w") String w,            @RequestParam(value = "imgFile") MultipartFile imageFile    ) throws Exception{        System.out.println("==========Start=============");        String realPath = request.getSession().getServletContext().getRealPath("/");        String resourcePath = "resources/uploadImages/";        if(imageFile!=null){            if(FileUploadUtil.allowUpload(imageFile.getContentType())){                String fileName = FileUploadUtil.rename(imageFile.getOriginalFilename());                int end = fileName.lastIndexOf(".");                String saveName = fileName.substring(0,end);                File dir = new File(realPath + resourcePath);                if(!dir.exists()){                    dir.mkdirs();                }                File file = new File(dir,saveName+"_src.jpg");                imageFile.transferTo(file);                String srcImagePath = realPath + resourcePath + saveName;                int imageX = Integer.parseInt(x);                int imageY = Integer.parseInt(y);                int imageH = Integer.parseInt(h);                int imageW = Integer.parseInt(w);                //这里开始截取操作                System.out.println("==========imageCutStart=============");                ImgCut.imgCut(srcImagePath,imageX,imageY,imageW,imageH);                System.out.println("==========imageCutEnd=============");                request.getSession().setAttribute("imgSrc",resourcePath + saveName+"_src.jpg");//成功之后显示用                request.getSession().setAttribute("imgCut",resourcePath + saveName+"_cut.jpg");//成功之后显示用            }        }        return "success";    }}

图片裁剪工具类:

package com.springjcrop.demo;import java.awt.Graphics;import java.awt.Image;import java.awt.Toolkit;import java.awt.image.BufferedImage;import java.awt.image.CropImageFilter;import java.awt.image.FilteredImageSource;import java.awt.image.ImageFilter;import java.io.File;import javax.imageio.ImageIO;public class ImgCut {    /**     * 截取图片     * @param srcImageFile  原图片地址     * @param x    截取时的x坐标     * @param y    截取时的y坐标     * @param desWidth   截取的宽度     * @param desHeight   截取的高度     */    public static void imgCut(String srcImageFile, int x, int y, int desWidth,                              int desHeight) {        try {            Image img;            ImageFilter cropFilter;            BufferedImage bi = ImageIO.read(new File(srcImageFile+"_src.jpg"));            int srcWidth = bi.getWidth();            int srcHeight = bi.getHeight();            if (srcWidth >= desWidth && srcHeight >= desHeight) {                Image image = bi.getScaledInstance(srcWidth, srcHeight,Image.SCALE_DEFAULT);                cropFilter = new CropImageFilter(x, y, desWidth, desHeight);                img = Toolkit.getDefaultToolkit().createImage(                        new FilteredImageSource(image.getSource(), cropFilter));                BufferedImage tag = new BufferedImage(desWidth, desHeight,                        BufferedImage.TYPE_INT_RGB);                Graphics g = tag.getGraphics();                g.drawImage(img, 0, 0, null);                g.dispose();                //输出文件                ImageIO.write(tag, "JPEG", new File(srcImageFile+"_cut.jpg"));            }        } catch (Exception e) {            e.printStackTrace();        }    }}

index.jsp 文件:

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><!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>demo</title><link rel="stylesheet" href="<c:url value="/resources/jcrop/css/jquery.Jcrop.css"/>" type="text/css"></link><script type="text/javascript" src="<c:url value="/resources/jcrop/js/jquery.min.js"/>"></script><script type="text/javascript" src="<c:url value="/resources/jcrop/js/jquery.Jcrop.js"/>"></script></head><body>    <form name="form" action="<%=request.getContextPath()%>/UploadDemo/uploadHeadImage" class="form-horizontal" method="post" enctype="multipart/form-data">        <div class="modal-body text-center">            <div class="zxx_main_con">                <div class="zxx_test_list">                    <input class="photo-file" type="file" name="imgFile" id="fcupload" onchange="readURL(this);" />                    <img alt="" src="" id="cutimg" />                     <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" />                </div>            </div>        </div>                <div id="preview-pane">            <div class="preview-container">                <img src="" class="jcrop-preview" alt="预览">            </div>        </div>                <div class="modal-footer">            <button id="submit" onclick="">上传</button>        </div>    </form>    <script type="text/javascript">        //定义一个全局api,这样操作起来比较灵活        var api = null,                 boundx,         boundy,                 $preview = $('#preview-pane'),         $pcnt = $('#preview-pane .preview-container'),         $pimg = $('#preview-pane .preview-container img'),        xsize = $pcnt.width(),         ysize = $pcnt.height();        function readURL(input) {            if (input.files && input.files[0]) {                var reader = new FileReader();                reader.readAsDataURL(input.files[0]);                reader.onload = function(e) {                    $('#cutimg').removeAttr('src');                    $('#cutimg').attr('src', e.target.result);                    $pimg.removeAttr('src');                    $pimg.attr('src', e.target.result);                    api = $.Jcrop('#cutimg', {                        setSelect: [ 20, 20, 200, 200 ],                        aspectRatio: 1,                        onSelect: updateCoords,                        onChange:updateCoords                    });                    var bounds = api.getBounds();                    boundx = bounds[0];                    boundy = bounds[1];                    $preview.appendTo(api.ui.holder);                };                if (api != undefined) {                    api.destroy();                }            }            function updateCoords(obj) {                $("#x").val(obj.x);                $("#y").val(obj.y);                $("#w").val(obj.w);                $("#h").val(obj.h);                if (parseInt(obj.w) > 0) {                    var rx = xsize / obj.w;                    var ry = ysize / obj.h;                    $pimg.css({                        width : Math.round(rx * boundx) + 'px',                        height : Math.round(ry * boundy) + 'px',                        marginLeft : '-' + Math.round(rx * obj.x) + 'px',                        marginTop : '-' + Math.round(ry * obj.y) + 'px'                    });                }            }            ;        }    </script></body></html>

OK,基本的东西装备完毕了。

下面就是期待见证奇迹的时刻了,开始放大招了:


 

0 0