The NoteBook of EricKong

            BlogJava :: 首頁 :: 聯(lián)系 :: 聚合  :: 管理
            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.     // 輸入?yún)?shù):上傳過來的文件路徑  
          46.     private File file;  
          47.   
          48.     /** 
          49.      * 輸 入?yún)?shù):文件名稱 由struts的攔截器默認賦值,注意setter的寫法:file+fileName 
          50.      */  
          51.     private String fileName;  
          52.   
          53.     /** 
          54.      * 輸 入?yún)?shù) 由struts的攔截器默認賦值,注意setter的寫法:file+contentType 
          55.      */  
          56.     private String contentType;  
          57.   
          58.     // 輸出參數(shù)  
          59.     private String imageFileName;  
          60.   
          61.     // 輸出參數(shù):原圖保存路徑  
          62.     private String ipath;  
          63.       
          64.     // 輸出參數(shù):縮略圖保存路徑  
          65.     private String imgPath;  
          66.   
          67.     // 輸出參數(shù)  
          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.         // 創(chuàng)建子目錄 得到添加水印后的圖片的存儲路徑,子目錄只能一級一級的建  
          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.             // 創(chuàng)建一個FileInputStream對象從源圖片獲取數(shù)據(jù)流  
          243.             FileInputStream sFile = new FileInputStream(img);  
          244.   
          245.             // 創(chuàng)建一個Image對象并以源圖片數(shù)據(jù)流填充  
          246.             Image src = ImageIO.read(sFile);  
          247.   
          248.             // 得到源圖寬  
          249.             int width = src.getWidth(null);  
          250.             // 得到源圖長  
          251.             int height = src.getHeight(null);  
          252.   
          253.             // 創(chuàng)建一個BufferedImage來作為圖像操作容器  
          254.             BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
          255.             // 創(chuàng)建一個繪圖環(huán)境來進行繪制圖象  
          256.             Graphics2D g = image.createGraphics();  
          257.             // 將原圖像數(shù)據(jù)流載入這個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.             // 創(chuàng)建輸出文件流  
          272.             FileOutputStream outi = new FileOutputStream(img);  
          273.             // 創(chuàng)建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 閱讀(1792) 評論(0)  編輯  收藏 所屬分類: struts2
          主站蜘蛛池模板: 额济纳旗| 永春县| 略阳县| 张家界市| 娄底市| 东兴市| 灯塔市| 平江县| 华亭县| 专栏| 上虞市| 长春市| 邹平县| 竹溪县| 竹山县| 海城市| 竹北市| 游戏| 当雄县| 大新县| 沈丘县| 温州市| 云南省| 平邑县| 黄大仙区| 龙江县| 凤山县| 城市| 南乐县| 会泽县| 彩票| 鹤峰县| 长顺县| 马公市| 乐亭县| 伊金霍洛旗| 宝坻区| 塔城市| 新巴尔虎左旗| 郓城县| 涟水县|