图片的截取上传,终于写出来了!

需要的包

项目的演示

项目的根目录

index.jsp

<body>
<!-- 用来上传图片 -->
<form action="${pageContext.request.contextPath }/uploadPic" method="post" enctype="multipart/form-data">
        photo:<input type="file" name="photo"><br>
        <input type="submit" value="submit">
        
    </form><br>
    
    <!-- 用来接收截取后的图片 -->
    <div style="width:120px;height:120px;overflow:hidden;">

        <img src="cutImage/${mess}" height="120px" width="120px"/>
    </div>
</body>

对应的后台servlet代码,uploadPic.java

package com.yunqing.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.RequestContext;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;


public class uploadPic extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //得到文件上传的保存目录,放在WEB-INF下会更安全,但是不允许外界直接访问,所以放在根目录下的/image中
        String fileSavePath=this.getServletContext().getRealPath("/image");
        
        File file=new File(fileSavePath);
        //判断文件夹是否存在
        if(!file.exists()&&!file.isDirectory()){
            //不存在则创建
            file.mkdir();
        }
        //转发的消息
        String message="";
        //文件名+后缀名
        String fileNameAndExt="";
        
    try {
        //使用Apache文件上传组件处理文件上传步骤:
        //1、创建一个DiskFileItemFactory工厂
        DiskFileItemFactory factory=new DiskFileItemFactory();
        //2、创建一个文件上传解析器
        ServletFileUpload upload=new ServletFileUpload(factory);
        //解决上传文件名的中文乱码
        upload.setHeaderEncoding("UTF-8");
        //3、判断提交上来的数据是否是上传表单的数据
        if(!ServletFileUpload.isMultipartContent(request)){
            //按照传统方式获取数据
            return;
        }
        //4、使用ServletFileUpload解析器解析上传数据,解析结果返回的是一个List<FileItem>集合,每一个FileItem对应一个Form表单的输入项
            List<FileItem> list=upload.parseRequest((RequestContext) new ServletRequestContext(request));
            for (FileItem fileItem : list) {
                //如果fileitem中封装的是普通输入项的数据
                if(fileItem.isFormField()){//是普通的表单类型
                    String name=fileItem.getFieldName();
                    //解决普通输入项的数据的中文乱码问题
                    String value=fileItem.getString("UTF-8");
                    System.out.println(name+"="+value);
                }else{//不是普通的表单类型,file类型
                    
                    //如果fileitem中封装的是上传文件
                    //得到上传的文件名称
                    String filename=fileItem.getName();
                    if(filename==null||"".equals(filename)){
                        continue;
                    }
                    //注意:不同的浏览器提交的文件名是不一样的,有些浏览器提交上来的文件名是带有路径的,如:  c:\a\b\1.txt,而有些只是单纯的文件名,如:1.txt
                    //处理获取到的上传文件的文件名的路径部分,只保留文件名部分
                    filename=filename.substring(filename.lastIndexOf("\\")+1);
                    //获取后缀名
                    String fileExtName=filename.substring(filename.lastIndexOf(".")+1);
                    
                    System.out.println("文件的后缀名是"+fileExtName);
                    //获取item中的上传文件的输入流
                    InputStream is=fileItem.getInputStream();
                    
                    //FileOutputStream fos=new FileOutputStream(fileSavePath+"\\"+filename);
                    
                    StringBuffer fileSaveName=this.fileSaveName();
                    
                    fileNameAndExt=fileSaveName+"."+fileExtName;
                    
                    System.out.println(fileNameAndExt);
                    //创建一个文件输出流            
                    FileOutputStream fos=new FileOutputStream(fileSavePath+"\\"+fileSaveName+"."+fileExtName);    
                    //创建一个缓冲区
                    byte buffer[]=new byte[1024];
                    //判断输入流中的数据是否已经读完的标识
                    int len=0;
                    
                    //len=is.read(buffer);
                    //循环将输入流读入到缓冲区当中,(len=in.read(buffer))>0就表示in里面还有数据
                    while((len=is.read(buffer))>-1){
                        //使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中
                        fos.write(buffer, 0, len);
                    }
                    //关闭输入流
                    is.close();
                    //关闭输出流
                    fos.close();
                    //删除处理文件上传时生成的临时文件
                    fileItem.delete();
                    
                    message="文件上传成功";
                    message=fileNameAndExt;
                    

                }
            }
        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            message="文件上传失败";
            e.printStackTrace();
        }
        request.setAttribute("message", message);
        request.getRequestDispatcher("/message.jsp").forward(request, response);
        
        HttpSession hs=request.getSession();
        hs.setAttribute("message", message);
    }
/**
 * 给上传的文件命名    
 * @return
 */
    public StringBuffer fileSaveName(){
        StringBuffer dname=new StringBuffer();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmssSSS");
        Date d=new Date();
        dname.append(sdf.format(d));
        
        //生成四位随机数
        Random random = new Random();
        for(int i=0;i<4;i++){
            dname.append(random.nextInt(10));
        }
        return dname;
    }
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
                  throws ServletException, IOException {
      
             doGet(request, response);
         } 

}

截取的jsp页面

<%@ page language="java" contentType="text/html; 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=ISO-8859-1">
<title>Insert title here</title>
<script src="js/jquery.min.js" type="text/javascript"></script>
    <script src="js/jquery-ui.min.js" type="text/javascript"></script>
    <script src="js/jquery.Jcrop.js" type="text/javascript"></script>
    <link rel="stylesheet" href="css/jquery-ui.css" type="text/css" />
    <link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />
</head>
<body>
    <img src="image/${message}" id="cutPic"><br>
    <h2>剪切预览:</h2>    
    <div style="width:120px;height:120px;overflow:hidden;">

        <img src="image/${message}" id="preview" class="jcrop-preview" height="120px" width="120px"/>
    </div><br>
    
    
    <form id="uploadSubForm" action="${pageContext.request.contextPath }/UploadSubImage" method="post">
          <div>
          <input type="text" size="4" id="startX" name="startX" />
          <input type="text" size="4" id="startY" name="startY" />
          <input type="text" size="4" id="endX" name="endX" />
          <input type="text" size="4" id="endY" name="endY" />
          <input type="text" size="4" id="width" name="width" />
          <input type="text" size="4" id="height" name="height" />
          </div>
          <input type="submit" id="uploadBtn" name="uploadBtn" value="submit" onclick="uploadSubImage()">
      </form>
</body>
<script type="text/javascript">
jQuery(function($){
    var jcrop_api, boundx, boundy;
    
    $('#cutPic').Jcrop({
        onChange: updatePreview,
        onSelect: updatePreview,
        aspectRatio: 1
    },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;
    });
        
        function updatePreview(c)
          {
              //得到坐标
              $('#startX').val(c.x);
              $('#startY').val(c.y);
              $('#endX').val(c.x2);
              $('#endY').val(c.y2);
              $('#width').val(c.w);
              $('#height').val(c.h);

              //预览效果
              if (parseInt(c.w) > 0)
              {
              var rx = 120 / c.w;
              var ry = 120 / c.h;

              $('#preview').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 uploadSubImage() {
                document.getElementById('uploadSubForm').submit();
            } 

});
</script>
</html>

截取的后台操作的servlet

UploadSubImage.java
package com.yunqing.servlet;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class UploadSubImage extends HttpServlet {
    //截取后的图片
    private static BufferedImage subImg;
    //转发的消息
    String mess="";
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*HttpSession hs=request.getSession();
        hs.setAttribute("message", message);*/
        //根据uploadPic中的上边两行代码,得到源图片文件的名称+后缀名
        HttpSession hs=request.getSession();
        
        String str=hs.getAttribute("message").toString();
        
        String srcFileName=this.getServletContext().getRealPath("/image")+"\\"+str.toString();//得到上传的原图地址
        //得到后缀名
        String Ext=srcFileName.substring(srcFileName.lastIndexOf(".")+1);
        
        //System.out.println(request.getParameter("startX"));
        //剪切后的图片保存地址
        String cutImgSavePath=this.getServletContext().getRealPath("/cutImage");
        
        
        
        File file=new File(cutImgSavePath);
        
        if(!file.exists()&&!file.isDirectory()){
            file.mkdir();
        }
        //得到message.jsp传过来的截取尺寸
        int startX = Math.round(Float.parseFloat(request.getParameter("startX")));
        int startY = Math.round(Float.parseFloat(request.getParameter("startY")));
        int endX = Math.round(Float.parseFloat(request.getParameter("endX")));
        int endY = Math.round(Float.parseFloat(request.getParameter("endY")));
        int width = Math.round(Float.parseFloat(request.getParameter("width")));
        int height = Math.round(Float.parseFloat(request.getParameter("height")));
        System.out.println(startX + "==" + startY + "==" + endX + "==" + endY + "==" + width + "==" + height);
        //截图
        cut(srcFileName, startX, startY, width, height);
        //截图后的图片命名
        String cutName=this.cutImgFileName().toString();
        //保存
        save(Ext, cutName, cutImgSavePath, width, height);
        //传图片名称+后缀名
        mess=cutName+"."+Ext;
        
        request.setAttribute("mess", mess);
        request.getRequestDispatcher("index.jsp").forward(request, response);
        
    }
    
    public static void cut(String srcFileName,int startX,int startY,int width,int height){
        try {
            BufferedImage bufImg = ImageIO.read(new FileInputStream(srcFileName));
            subImg=bufImg.getSubimage(startX, startY, width, height);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public static void save(String imgExt,String imgName,String cutPath,int width,int height){
        UploadSubImage u=new UploadSubImage();
        try {/**压缩图片为指定尺寸*/
            if(subImg.getWidth()!=width || subImg.getHeight()!=height){
                BufferedImage tempImg = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
                tempImg.getGraphics().drawImage(subImg.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0,null);
                ImageIO.write(tempImg, imgExt, new File(cutPath+"/"+imgName+"."+imgExt));
            }else{
                ImageIO.write(subImg,imgExt,new File(cutPath+"/"+imgName+"."+imgExt));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    
    public StringBuffer cutImgFileName(){
        StringBuffer dname=new StringBuffer();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmssSSS");
        Date d=new Date();
        dname.append(sdf.format(d));
        
        //生成四位随机数
        Random random = new Random();
        for(int i=0;i<4;i++){
            dname.append(random.nextInt(10));
        }
        return dname;
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

 

posted @ 2017-07-25 15:19  云晴  阅读(2838)  评论(0编辑  收藏  举报