The NoteBook of EricKong

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  611 Posts :: 1 Stories :: 190 Comments :: 0 Trackbacks

1、页面代码

Html代码
  1. <%@ page contentType="text/html;charset=UTF-8"%>  
  2. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  
  3. <html>  
  4. <head>  
  5. <title>图片上传</title>  
  6. <script type="text/javascript">  
  7.         function upload(){  
  8.             var ff = document.forms.imageForm;  
  9.             var img = ff.file.value;  
  10.             if(img==null || img==""){  
  11.                 alert(" 图片路径不允许为空!");  
  12.                 return;  
  13.             }  
  14.             ff.target="_top";  
  15.             ff.method="post";  
  16.             ff.submit();  
  17.         }  
  18.     </script>  
  19.   
  20.     </head>  
  21.   
  22.     <body>  
  23.         <form id="imageForm" action="image.action"  
  24.             enctype="multipart/form-data">  
  25.             <p>  
  26.                 ------------------------------  
  27.   
  28.             </p>  
  29.             上 传图片:  
  30.             <input name="file" type=file value=''>  
  31.             <br>  
  32.             <input type="button" value="上传" onclick="upload()"  
  33.                 style="cursor: pointer">  
  34.         </form>  
  35.         <p>  
  36.             -------------------------------------------------  
  37.         </p>  
  38.         <div>  
  39.             <c:if test="${ipath!=null}">  
  40.                 <img src="${ipath}">  
  41.             </c:if>  
  42.         <div>  
  43.         <div>  
  44.             <c:if test="${imgPath!=null}">  
  45.                 <img src="${imgPath}">  
  46.             </c:if>  
  47.         </div>  
  48.     </body>  
  49. </html>  

2、action代码

Java代码
  1. import java.awt.AlphaComposite;  
  2. import java.awt.Color;  
  3. import java.awt.Font;  
  4. import java.awt.Graphics2D;  
  5. import java.awt.Image;  
  6. import java.awt.geom.AffineTransform;  
  7. import java.awt.image.AffineTransformOp;  
  8. import java.awt.image.BufferedImage;  
  9. import java.io.BufferedInputStream;  
  10. import java.io.BufferedOutputStream;  
  11. import java.io.File;  
  12. import java.io.FileInputStream;  
  13. import java.io.FileNotFoundException;  
  14. import java.io.FileOutputStream;  
  15. import java.io.IOException;  
  16. import java.io.InputStream;  
  17. import java.io.OutputStream;  
  18. import java.util.Date;  
  19.   
  20. import javax.imageio.ImageIO;  
  21.   
  22. import org.apache.commons.logging.Log;  
  23. import org.apache.commons.logging.LogFactory;  
  24. import org.apache.struts2.ServletActionContext;  
  25.   
  26. import com.opensymphony.xwork2.ActionSupport;  
  27. import com.sun.image.codec.jpeg.JPEGCodec;  
  28. import com.sun.image.codec.jpeg.JPEGImageEncoder;  
  29.   
  30. public class ImageAction extends ActionSupport {  
  31.   
  32.     /** 
  33.      * 图 片上传、缩放、文字水印、图片水印 
  34.      */  
  35.     private static final long serialVersionUID = -8982586906724587883L;  
  36.   
  37.     private Log log = LogFactory.getLog(getClass());  
  38.   
  39.     private static final int BUFFER_SIZE = 16 * 1024;  
  40.   
  41.     private static final String TEXT_TITLE = "文字水印";  
  42.       
  43.     private static final String WATER_IMG_NAME = "rzx.gif";  
  44.   
  45.     // 输入参数:上传过来的文件路径  
  46.     private File file;  
  47.   
  48.     /** 
  49.      * 输 入参数:文件名称 由struts的拦截器默认赋值,注意setter的写法:file+fileName 
  50.      */  
  51.     private String fileName;  
  52.   
  53.     /** 
  54.      * 输 入参数 由struts的拦截器默认赋值,注意setter的写法:file+contentType 
  55.      */  
  56.     private String contentType;  
  57.   
  58.     // 输出参数  
  59.     private String imageFileName;  
  60.   
  61.     // 输出参数:原图保存路径  
  62.     private String ipath;  
  63.       
  64.     // 输出参数:缩略图保存路径  
  65.     private String imgPath;  
  66.   
  67.     // 输出参数  
  68.     private String json;  
  69.   
  70.     public ImageAction() {  
  71.   
  72.     }  
  73.   
  74.     @Override  
  75.     public String execute() throws Exception {  
  76.         return uploadImage();  
  77.     }  
  78.   
  79.     /** 
  80.      * 得 到文件名称 
  81.      *  
  82.      * @param fileName 
  83.      * @return 
  84.      */  
  85.     private String getExtention(String fileName) {  
  86.         int pos = fileName.lastIndexOf(".");  
  87.         return fileName.substring(pos);  
  88.     }  
  89.   
  90.     /** 
  91.      * 拷 贝 
  92.      *  
  93.      * @param file 
  94.      * @param imageFile 
  95.      * @throws Exception 
  96.      */  
  97.     private void copy(File src, File dist) throws Exception {  
  98.         log.debug("[src]--" + src);  
  99.         log.debug("[dist]--" + dist);  
  100.   
  101.         try {  
  102.             InputStream in = null;  
  103.             OutputStream out = null;  
  104.             try {  
  105.                 in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);  
  106.                 out = new BufferedOutputStream(new FileOutputStream(dist), BUFFER_SIZE);  
  107.   
  108.                 byte[] buf = new byte[BUFFER_SIZE];  
  109.                 while (in.read(buf) > 0) {  
  110.                     out.write(buf);  
  111.                 }  
  112.                 out.close();  
  113.                 in.close();  
  114.             } catch (FileNotFoundException e) {  
  115.                 e.printStackTrace();  
  116.             } catch (IOException e) {  
  117.                 e.printStackTrace();  
  118.             } finally {  
  119.                 if (in != null)  
  120.                     in.close();  
  121.                 if (out != null)  
  122.                     out.close();  
  123.             }  
  124.         } catch (Exception e) {  
  125.             e.printStackTrace();  
  126.             throw new Exception(e);  
  127.         }  
  128.   
  129.     }  
  130.   
  131.     /** 
  132.      * 图 片上传 
  133.      *  
  134.      * @return 
  135.      */  
  136.     public String uploadImage() throws Exception {  
  137.         log.debug("[file]--" + file);  
  138.         log.debug("[file name]--" + fileName);  
  139.         imageFileName = new Date().getTime() + getExtention(fileName);  
  140.   
  141.         // 得到文件存放路径  
  142.         log.debug("[imageFileName]--" + imageFileName);  
  143.         String dir = ServletActionContext.getServletContext().getRealPath("/UploadImages");  
  144.         File dirs = new File(dir);  
  145.         if (!dirs.exists())  
  146.             dirs.mkdir();  
  147.   
  148.         // 使用原来的文件名保存图片  
  149.         String path = dir + "/" + fileName;  
  150.         File imageFile = new File(path);  
  151.   
  152.         copy(file, imageFile);  
  153.   
  154.         // 缩放  
  155.         zoom(imageFile);  
  156.   
  157.         // 给大图添加文字水印  
  158. //      watermark(imageFile);  
  159.         // 给大图添加图片水印,可以是gif或png格式  
  160.         imageWaterMark(imageFile);  
  161.   
  162.         // 创建子目录 得到添加水印后的图片的存储路径,子目录只能一级一级的建  
  163.         String dist = dir + "/water";  
  164.         File outFile = new File(dist);  
  165.         if (!outFile.exists())  
  166.             outFile.mkdir();  
  167.         File sImgpath = new File(dist + "/" + fileName);  
  168.   
  169.         // 给小图添加文字水印  
  170.     //  watermark(sImgpath);  
  171.         // 给小图添加图片水印,可以是gif或png格式  
  172.         imageWaterMark(sImgpath);  
  173.   
  174.         // 大图路径  
  175.         ipath = "UploadImages/" + fileName;  
  176.         // 小图路径  
  177.         imgPath = "UploadImages/water/" + fileName;  
  178.   
  179.         return SUCCESS;  
  180.     }  
  181.   
  182.     /** 
  183.      * 缩 放处理 
  184.      *  
  185.      * @return 
  186.      */  
  187.     public void zoom(File imageFile) throws Exception {  
  188.         log.debug("[zoom][imageFile]--" + imageFile);  
  189.         try {  
  190.   
  191.             // 缩略图存放路径  
  192.             File todir = new File(ServletActionContext.getServletContext().getRealPath("/UploadImages") + "/water");  
  193.             if (!todir.exists()) {  
  194.                 todir.mkdir();  
  195.             }  
  196.   
  197.             if (!imageFile.isFile())  
  198.                 throw new Exception(imageFile + " is not image file error in CreateThumbnail!");  
  199.   
  200.             File sImg = new File(todir, fileName);  
  201.   
  202.             BufferedImage Bi = ImageIO.read(imageFile);  
  203.             // 假设图片宽 高 最大为130 80,使用默认缩略算法  
  204.             Image Itemp = Bi.getScaledInstance(130, 80, Bi.SCALE_DEFAULT);  
  205.   
  206.             double Ratio = 0.0;  
  207.             if ((Bi.getHeight() > 130) || (Bi.getWidth() > 80)) {  
  208.                 if (Bi.getHeight() > Bi.getWidth())  
  209.                     Ratio = 80.0 / Bi.getHeight();  
  210.                 else  
  211.                     Ratio = 130.0 / Bi.getWidth();  
  212.   
  213.                 AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(Ratio, Ratio), null);  
  214.                 Itemp = op.filter(Bi, null);  
  215.             }  
  216.   
  217.             ImageIO.write((BufferedImage) Itemp, "jpg", sImg);  
  218.               
  219.         } catch (IOException e) {  
  220.             e.printStackTrace();  
  221.             throw new Exception(e);  
  222.         }  
  223.     }  
  224.   
  225.     /** 
  226.      * 添 加文字水印 
  227.      *  
  228.      * @return 
  229.      * @throws Exception 
  230.      * @throws Exception 
  231.      */  
  232.     public void watermark(File img) throws Exception {  
  233.         log.debug("[watermark file name]--" + img.getPath());  
  234.         try {  
  235.   
  236.             if (!img.exists()) {  
  237.                 throw new IllegalArgumentException("file not found!");  
  238.             }  
  239.   
  240.             log.debug("[watermark][img]--" + img);  
  241.   
  242.             // 创建一个FileInputStream对象从源图片获取数据流  
  243.             FileInputStream sFile = new FileInputStream(img);  
  244.   
  245.             // 创建一个Image对象并以源图片数据流填充  
  246.             Image src = ImageIO.read(sFile);  
  247.   
  248.             // 得到源图宽  
  249.             int width = src.getWidth(null);  
  250.             // 得到源图长  
  251.             int height = src.getHeight(null);  
  252.   
  253.             // 创建一个BufferedImage来作为图像操作容器  
  254.             BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
  255.             // 创建一个绘图环境来进行绘制图象  
  256.             Graphics2D g = image.createGraphics();  
  257.             // 将原图像数据流载入这个BufferedImage  
  258.             log.debug("width:" + width + " height:" + height);  
  259.             g.drawImage(src, 0, 0, width, height, null);  
  260.             // 设定文本字体  
  261.             g.setFont(new Font("宋体", Font.BOLD, 28));  
  262.             String rand = TEXT_TITLE;  
  263.             // 设定文本颜色  
  264.             g.setColor(Color.blue);  
  265.             // 设置透明度  
  266.             g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f));  
  267.             // 向BufferedImage写入文本字符,水印在图片上的坐标  
  268.             g.drawString(rand, width - (width - 20), height - (height - 60));  
  269.             // 使更改生效  
  270.             g.dispose();  
  271.             // 创建输出文件流  
  272.             FileOutputStream outi = new FileOutputStream(img);  
  273.             // 创建JPEG编码对象  
  274.             JPEGImageEncoder encodera = JPEGCodec.createJPEGEncoder(outi);  
  275.             // 对这个BufferedImage (image)进行JPEG编码  
  276.             encodera.encode(image);  
  277.             // 关闭输出文件流  
  278.             outi.close();  
  279.             sFile.close();  
  280.   
  281.         } catch (IOException e) {  
  282.             e.printStackTrace();  
  283.             throw new Exception(e);  
  284.         }  
  285.     }  
  286.   
  287.     /** 
  288.      * 添 加图片水印 
  289.      *  
  290.      */  
  291.     public void imageWaterMark(File imgFile) throws Exception {  
  292.         try {  
  293.             // 目标文件  
  294.             Image src = ImageIO.read(imgFile);  
  295.             int wideth = src.getWidth(null);  
  296.             int height = src.getHeight(null);  
  297.             BufferedImage image = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB);  
  298.             Graphics2D g = image.createGraphics();  
  299.             g.drawImage(src, 0, 0, wideth, height, null);  
  300.               
  301.             // 水印文件 路径  
  302.             String waterImgPath = ServletActionContext.getServletContext().getRealPath("/UploadImages")+"/"+WATER_IMG_NAME;  
  303.             File waterFile = new File(waterImgPath);  
  304.             Image waterImg = ImageIO.read(waterFile);  
  305.               
  306.             int w_wideth = waterImg.getWidth(null);  
  307.             int w_height = waterImg.getHeight(null);  
  308.             g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f));  
  309.             g.drawImage(waterImg, (wideth - w_wideth) / 2, (height - w_height) / 2, w_wideth, w_height, null);  
  310.             // 水印文件结束  
  311.               
  312.             g.dispose();  
  313.             FileOutputStream out = new FileOutputStream(imgFile);  
  314.             JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
  315.             encoder.encode(image);  
  316.             out.close();  
  317.         } catch (Exception e) {  
  318.             e.printStackTrace();  
  319.         }  
  320.     }  
  321.   
  322.     public void setFile(File file) {  
  323.         this.file = file;  
  324.     }  
  325.   
  326.     public String getIpath() {  
  327.         return ipath;  
  328.     }  
  329.   
  330.     public void setFileFileName(String fileName) {  
  331.         this.fileName = fileName;  
  332.     }  
  333.   
  334.     public void setImageFileName(String imageFileName) {  
  335.         this.imageFileName = imageFileName;  
  336.     }  
  337.   
  338.     public String getJson() {  
  339.         return json;  
  340.     }  
  341.   
  342.     public void setFileContentType(String fileContentType) {  
  343.         this.contentType = fileContentType;  
  344.     }  
  345.   
  346.     public String getImgPath() {  
  347.         return imgPath;  
  348.     }  
  349.   
  350. }  

3、struts.xml配置文件

Xml代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3. <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "struts-2.0.dtd" >  
  4. <struts>  
  5.     <include file="struts-default.xml" />  
  6.   
  7.     <constant name="struts.objectFactory" value="spring" />  
  8.     <constant name="struts.devMode" value="false" />  
  9.     <constant name="struts.locale" value="zh_CN" />  
  10.     <constant name="struts.multipart.maxSize" value="10000000000000" />  
  11.     <constant name="struts.i18n.encoding" value="utf-8" />  
  12.   
  13.     <package name="test" extends="struts-default">  
  14.         <interceptors>  
  15.             <interceptor-stack name="commonsStack">  
  16.                 <interceptor-ref name="exception"></interceptor-ref>  
  17.                 <interceptor-ref name="prepare" />  
  18.                 <interceptor-ref name="params" />  
  19.                 <interceptor-ref name="validation" />  
  20.                 <interceptor-ref name="workflow" />  
  21.             </interceptor-stack>  
  22.             <interceptor-stack name="uploadStack">  
  23.                 <interceptor-ref name="fileUpload">  
  24.                     <!-- 配置允许上传的文件类型  -->  
  25.                     <param name="allowedTypes">  
  26.                         image/bmp,image/png,image/gif,image/jpeg,image/jpg  
  27.                     </param>  
  28.                     <!-- 配置允许上传的文件大小  -->  
  29.                     <param name="maximumSize">50485760</param>  
  30.                     <!-- 50M=50*1024*1024 byte-->  
  31.                 </interceptor-ref>  
  32.                 <interceptor-ref name="commonsStack" />  
  33.             </interceptor-stack>  
  34.         </interceptors>  
  35.   
  36.         <!-- 默认拦截器 -->  
  37.         <default-interceptor-ref name="commonsStack" />  
  38.     </package>  
  39.       
  40.     <package name="image" extends="test">  
  41.         <action name="image" class="imageAction">  
  42.             <interceptor-ref name="uploadStack"></interceptor-ref>  
  43.             <result name="input">/image.jsp</result>  
  44.             <result name="success">/image.jsp</result>  
  45.         </action>  
  46.     </package>  
  47. </struts>  

 4、spring的配置比较简单就不贴了,在<beans>里加入一个bean就可以了。

以上完毕!

posted on 2010-07-14 21:26 Eric_jiang 阅读(1768) 评论(0)  编辑  收藏 所属分类: struts2

只有注册用户登录后才能发表评论。


网站导航: