struts2上传图片并剪切

jopen 10年前

上传图片的jsp页面

 <style type="text/css">  input {  vertical-align: middle;  margin: 0;  padding: 0  }      .file-box {  position: relative;  width: 340px  }      .txt {  height: 22px;  border: 1px solid #cdcdcd;  width: 180px;  }      .btn {  background-color: #FFF;  border: 1px solid #CDCDCD;  height: 24px;  width: 70px;  }      .file {  position: absolute;  top: 0;  right: 80px;  height: 24px;  filter: alpha(opacity : 0);  opacity: 0;  width: 260px  }  /* 定制文件上传按钮  */  .u-upload {  display: inline-block;  *display: inline;  *zoom: 1;  position: relative;  overflow: hidden;  }      .u-upload button {  height: 22px;  padding: 0 10px;  border: 1px solid #ccc;  overflow: visible;  font-size: 14px;  color: #666;  background: #ddd;  }      .u-upload input {  position: absolute;  top: 0;  right: -1px;  font-size: 100px;  cursor: pointer;  opacity: 0;  filter: alpha(opacity = 0);  }      .u-upload:hover button {  border-color: #bbb;  color: #333;  background: #ccc;  }      a.u-upload,a.u-upload:hover {  text-decoration: none;  }  </style>    <script type='text/javascript'>  var file = $("#file").val();  var fileName = getFileName(file);  function getFileName(o) {  var pos = o.lastIndexOf("\\");  return o.substring(pos + 1);  }  <%--名字不要起upload!!!名字冲突!--%>  function upload1() {    document.commentform.action = "upload!upload";  document.commentform.submit();  }  function publish() {  document.commentform.action = "secondHandAction!putmessage";  document.commentform.submit();  }  </script>    <form method="post" id="commentform" name="commentform"  class="form" action="" ENCTYPE="multipart/form-data">  <textarea name="comment" type="text" placeholder="信息内容" rows="15"  class="span8" tabindex="4" aria-required='true'></textarea>  <input type='text' name='uploadFileName' id='uploadFileName'  class='txt' value="<%=Util.uploadFileUrl%>"/> <a href="#" class="u-upload">  <button type="button">浏览..</button> <input type="file"  name="upload" class="file" id="upload" size="28"  onchange="document.getElementById('uploadFileName').value=this.value" />  </a> <input name="submit" type="submit" value="上传"  class="btn btn-small btn-info" onClick="upload1()" /> </br>  </form> 

上传图片的Action类

 package com.efinance.action;      import java.io.File;  import java.io.FileInputStream;  import java.io.FileNotFoundException;  import java.io.FileOutputStream;  import java.io.IOException;  import java.io.InputStream;  import java.io.OutputStream;      import javax.servlet.http.HttpServletRequest;      import org.apache.struts2.ServletActionContext;  import org.apache.struts2.interceptor.ServletRequestAware;          import com.opensymphony.xwork2.ActionContext;  import com.opensymphony.xwork2.ActionSupport;  import com.utils.OperateImage;  import com.utils.Util;    public class FileUploadAction extends ActionSupport implements ServletRequestAware{  /**  *@author island  *@date 2011-08-13  */  private static final long serialVersionUID = 1L;  private File upload;  private String uploadContentType;  private String uploadFileName;  private String savePath;  FileInputStream inputStream;  protected HttpServletRequest request;    public void setServletRequest(HttpServletRequest request) {  this.request = request;    }  public String upload()  {  byte[] buffer=new byte[1024];  try  {  InputStream in=new FileInputStream(upload);  //上传的名字要改,不能按照用户上传的名字当名字  // String realPath =     System.out.println(this.getSavePath()+"\\"+uploadFileName);  //            ServletActionContext.getServletContext().getRealPath("/images");   OutputStream out=new FileOutputStream(new File(this.getSavePath()+"\\"+uploadFileName));    int length=in.read(buffer);  while(length>0)  {  out.write(buffer);  length=in.read(buffer);  }    in.close();  out.flush();  out.close();  }  catch(Exception e)  {  e.printStackTrace();  }  return this.SUCCESS;  }  public String download()  {  //以后uploadFileName来源于数据库  File file=new File(this.getSavePath()+"\\"+uploadFileName);  try {  inputStream=new FileInputStream(file);  } catch (FileNotFoundException e) {  e.printStackTrace();  }    return "downImg";  }    public String cut() throws IOException{  //x1,y1就够用了  但是如果前端放大了那个剪切框,x1和y1是不能控制住图片大小的需要加上x2和y2才能控制住  String x1 = request.getParameter("x1");  String x2 = request.getParameter("x2");  String y1 = request.getParameter("y1");  String y2 = request.getParameter("y2");  String width = request.getParameter("width");  String height = request.getParameter("height");  String hidimg = request.getParameter("hidimg");//获取图片名称,jsp中名字后期来源于数据库  OperateImage o = new OperateImage(Integer.parseInt(x1),Integer.parseInt(y1),Integer.parseInt(width),Integer.parseInt(height));  //将hidimg取出图片名字  hidimg=hidimg.trim();  hidimg=hidimg.substring(hidimg.lastIndexOf("/")+1);  System.out.println(""+hidimg);  o.setSrcpath(this.getSavePath()+"\\"+hidimg);  //源文件路径  // 获取服务器存储路径  /* String realPath =                ServletActionContext.getServletContext().getRealPath("/images");  */         o.setSubpath(this.getSavePath()+"\\_"+Util.uploadFileName); //目标路径   图片的名字要改         o.cut();  return "cut";  }    public String getSavePath() {  return ServletActionContext.getRequest().getRealPath(savePath);  }  public void setSavePath(String savePath) {  this.savePath = savePath;  }      public FileInputStream getInputStream() {  return inputStream;  }  public void setInputStream(FileInputStream inputStream) {  this.inputStream = inputStream;  }  public File getUpload() {  return upload;  }  public void setUpload(File upload) {  this.upload = upload;  }  public String getUploadContentType() {  return uploadContentType;  }  public void setUploadContentType(String uploadContentType) {  this.uploadContentType = uploadContentType;  }  public String getUploadFileName() {  return uploadFileName;  }  public void setUploadFileName(String uploadFileName) {  Util.uploadFileUrl=uploadFileName;  uploadFileName=uploadFileName.trim();  System.out.println(""+uploadFileName);   this.uploadFileName=uploadFileName.substring(uploadFileName.lastIndexOf("/")+1);  Util.uploadFileName=uploadFileName.substring(uploadFileName.lastIndexOf("/")+1);  }  // public void addActionError(String anErrorMessage){  //   String s=anErrorMessage;  //   System.out.println(s);  //  }  //  public void addActionMessage(String aMessage){  //   String s=aMessage;  //   System.out.println(s);  //    //  }  //  public void addFieldError(String fieldName, String errorMessage){  //   String s=errorMessage;  //   String f=fieldName;  //   System.out.println(s);  //   System.out.println(f);  //  }      } 



裁剪图片

 package com.utils;      import java.awt.Rectangle;  import java.awt.image.BufferedImage;  import java.io.File;  import java.io.FileInputStream;  import java.io.IOException;  import java.util.Iterator;      import javax.imageio.ImageIO;  import javax.imageio.ImageReadParam;  import javax.imageio.ImageReader;  import javax.imageio.stream.ImageInputStream;      import org.apache.struts2.ServletActionContext;      /**   *@author island   *@date 2011-08-13   */  public class OperateImage {  //===源图片路径名称如:c:\1.jpg       private String srcpath ;                //===剪切图片存放路径名称.如:c:\2.jpg      private String subpath ;            //===剪切点x坐标      private int x ;            private int y ;                 //===剪切点宽度      private int width ;           private int height ;           public OperateImage(){                    }       public OperateImage(int x,int y,int width,int height){           this.x = x ;           this.y = y ;           this.width = width ;              this.height = height ;      }            /** *//** *//** *//**        * 对图片裁剪,并把裁剪完蛋新图片保存 。       */      public void cut() throws IOException{                      FileInputStream is = null ;          ImageInputStream iis =null ;                 try{                 //读取图片文件              is = new FileInputStream(srcpath);                             /** *//**//*               * 返回包含所有当前已注册 ImageReader 的 Iterator,这些 ImageReader                * 声称能够解码指定格式。 参数:formatName - 包含非正式格式名称 .               *(例如 "jpeg" 或 "tiff")等 。                */              Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName("jpg");               ImageReader reader = it.next();               //获取图片流               iis = ImageIO.createImageInputStream(is);                               /** *//**//*                * <p>iis:读取源.true:只向前搜索 </p>.将它标记为 ‘只向前搜索’。               * 此设置意味着包含在输入源中的图像将只按顺序读取,可能允许 reader               * 避免缓存包含与以前已经读取的图像关联的数据的那些输入部分。               */              reader.setInput(iis,true) ;                            /** *//**//*                * <p>描述如何对流进行解码的类<p>.用于指定如何在输入时从 Java Image I/O                * 框架的上下文中的流转换一幅图像或一组图像。用于特定图像格式的插件               * 将从其 ImageReader 实现的 getDefaultReadParam 方法中返回                * ImageReadParam 的实例。                */              ImageReadParam param = reader.getDefaultReadParam();                              /** *//**//*               * 图片裁剪区域。Rectangle 指定了坐标空间中的一个区域,通过 Rectangle 对象               * 的左上顶点的坐标(x,y)、宽度和高度可以定义这个区域。                */               Rectangle rect = new Rectangle(x, y, width, height);                                            //提供一个 BufferedImage,将其用作解码像素数据的目标。               param.setSourceRegion(rect);                 /** *//**//*               * 使用所提供的 ImageReadParam 读取通过索引 imageIndex 指定的对象,并将               * 它作为一个完整的 BufferedImage 返回。               */              BufferedImage bi = reader.read(0,param);                                      //保存新图片              ImageIO.write(bi, "jpg", new File(subpath));              }                  finally{             if(is!=null)                is.close() ;                    if(iis!=null)                iis.close();         }                               }       public int getHeight() {         return height;     }       public void setHeight(int height) {         this.height = height;     }        public String getSrcpath() {         return srcpath;     }       public void setSrcpath(String srcpath) {         this.srcpath = srcpath;     }       public String getSubpath() {         return subpath;     }       public void setSubpath(String subpath) {        this.subpath = subpath;     }       public int getWidth() {         return width;     }       public void setWidth(int width) {         this.width = width;     }       public int getX() {         return x;     }       public void setX(int x) {         this.x = x;     }       public int getY() {         return y;     }       public void setY(int y) {         this.y = y;     }      public static void main(String[] args)throws Exception{         //可以单独运行尝试         String name = "d:\\imges.jpg";                 OperateImage o = new OperateImage(220,213,200,333);         o.setSrcpath(name);          o.setSubpath("D:\\2.jpg");         o.cut() ;                }      } 


显示裁剪图片的jsp页面(showImg.jsp)

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  <%@ taglib uri="/struts-tags" prefix="s"%>  <%  String path = request.getContextPath();  String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  %>      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">  <head>  <meta http-equiv="Content-type" content="text/html; charset=utf-8" />  <meta http-equiv="Content-Language" content="en-us" />  <title></title>  <script src="<%=basePath %>/js/prototype.js" type="text/javascript"></script>     <script src="<%=basePath %>/js/scriptaculous.js?load=builder,dragdrop" type="text/javascript"></script>  <script src="<%=basePath %>/js/cropper.js" type="text/javascript"></script>  <link rel="stylesheet" type="text/css" href="<%=basePath %>/css/cropper.css" media="all" />      <script type="text/javascript" charset="utf-8">    function onEndCrop( coords, dimensions ) {  $( 'x1' ).value = coords.x1;  $( 'y1' ).value = coords.y1;  $( 'x2' ).value = coords.x2;  $( 'y2' ).value = coords.y2;  $( 'width' ).value = dimensions.width;  $( 'height' ).value = dimensions.height;  }    // example with a preview of crop results, must have minimumm dimensions  Event.observe(   window,   'load',   function() {   new Cropper.ImgWithPreview(   'testImage',  {   minWidth: 100,   minHeight: 100,  ratioDim: { x: 100, y: 100 },  displayOnInit: true,   onEndCrop: onEndCrop,  previewWrap: 'previewArea'  }   )   }   );    /*  if( typeof(dump) != 'function' ) {  Debug.init(true, '/');    function dump( msg ) {  // Debug.raise( msg );  };  } else dump( '---------------------------------------\n' );  */    </script>  <link rel="stylesheet" type="text/css" href="debug.css" media="all" />  <style type="text/css">  label {   clear: left;  margin-left: 50px;  float: left;  width: 5em;  }    #testWrap {  width: 500px;  float: left;  margin: 20px 0 0 50px;  }    #previewArea {  margin: 20px; 0 0 20px;  float: left;  }    #results {  clear: both;  }  </style>  </head>  <body>   <form action="<%=basePath %>cut.action" method="post">  <br /><br />    <!-- 组件要显示的图片 -->      <div id="testWrap">  <img id="testImage" src ='upload/<s:property value ="uploadFileName" /> ' />          <br />           <s:property value ="caption" />   </div>    <div id="previewArea"></div>  <div id="results">  <p>  <label for="x1">x1:</label>  <input type="text" name="x1" id="x1" />  </p>  <p>  <label for="y1">y1:</label>  <input type="text" name="y1" id="y1" />  </p>  <p>  <label for="x2">x2:</label>  <input type="text" name="x2" id="x2" />  </p>  <p>  <label for="y2">y2:</label>  <input type="text" name="y2" id="y2" />  </p>  <p>  <label for="width">width:</label>  <input type="text" name="width" id="width" />  </p>  <p>  <label for="height">height</label>  <input type="text" name="height" id="height" />  <input type="hidden" name="hidimg" value="<s:property value ="uploadFileName" />"/>  </p>  </div>   <input type="submit" value="剪切"/>  </form>  </body>  </html> 



工具类

public class Util {  /**  * 存放文件名  */  public static String uploadFileName="";  /**  * 存放文件完整路径  */  public static String uploadFileUrl="";  public static int userId=0;  public static String number="";  }