1、頁面代碼
Html代碼
- <%@ page contentType="text/html;charset=UTF-8"%>
- <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
- <html>
- <head>
- <title>圖片上傳</title>
- <script type="text/javascript">
- function upload(){
- var ff = document.forms.imageForm;
- var img = ff.file.value;
- if(img==null || img==""){
- alert(" 圖片路徑不允許為空!");
- return;
- }
- ff.target="_top";
- ff.method="post";
- ff.submit();
- }
- </script>
- </head>
- <body>
- <form id="imageForm" action="image.action"
- enctype="multipart/form-data">
- <p>
- ------------------------------
- </p>
- 上 傳圖片:
- <input name="file" type=file value=''>
- <br>
- <input type="button" value="上傳" onclick="upload()"
- style="cursor: pointer">
- </form>
- <p>
- -------------------------------------------------
- </p>
- <div>
- <c:if test="${ipath!=null}">
- <img src="${ipath}">
- </c:if>
- <div>
- <div>
- <c:if test="${imgPath!=null}">
- <img src="${imgPath}">
- </c:if>
- </div>
- </body>
- </html>
2、action代碼
Java代碼
- import java.awt.AlphaComposite;
- import java.awt.Color;
- import java.awt.Font;
- import java.awt.Graphics2D;
- import java.awt.Image;
- import java.awt.geom.AffineTransform;
- import java.awt.image.AffineTransformOp;
- import java.awt.image.BufferedImage;
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- 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 java.util.Date;
- import javax.imageio.ImageIO;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import org.apache.struts2.ServletActionContext;
- import com.opensymphony.xwork2.ActionSupport;
- import com.sun.image.codec.jpeg.JPEGCodec;
- import com.sun.image.codec.jpeg.JPEGImageEncoder;
- public class ImageAction extends ActionSupport {
- /**
- * 圖 片上傳、縮放、文字水印、圖片水印
- */
- private static final long serialVersionUID = -8982586906724587883L;
- private Log log = LogFactory.getLog(getClass());
- private static final int BUFFER_SIZE = 16 * 1024;
- private static final String TEXT_TITLE = "文字水印";
- private static final String WATER_IMG_NAME = "rzx.gif";
- // 輸入參數:上傳過來的文件路徑
- private File file;
- /**
- * 輸 入參數:文件名稱 由struts的攔截器默認賦值,注意setter的寫法:file+fileName
- */
- private String fileName;
- /**
- * 輸 入參數 由struts的攔截器默認賦值,注意setter的寫法:file+contentType
- */
- private String contentType;
- // 輸出參數
- private String imageFileName;
- // 輸出參數:原圖保存路徑
- private String ipath;
- // 輸出參數:縮略圖保存路徑
- private String imgPath;
- // 輸出參數
- private String json;
- public ImageAction() {
- }
- @Override
- public String execute() throws Exception {
- return uploadImage();
- }
- /**
- * 得 到文件名稱
- *
- * @param fileName
- * @return
- */
- private String getExtention(String fileName) {
- int pos = fileName.lastIndexOf(".");
- return fileName.substring(pos);
- }
- /**
- * 拷 貝
- *
- * @param file
- * @param imageFile
- * @throws Exception
- */
- private void copy(File src, File dist) throws Exception {
- log.debug("[src]--" + src);
- log.debug("[dist]--" + dist);
- try {
- InputStream in = null;
- OutputStream out = null;
- try {
- in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
- out = new BufferedOutputStream(new FileOutputStream(dist), BUFFER_SIZE);
- byte[] buf = new byte[BUFFER_SIZE];
- while (in.read(buf) > 0) {
- out.write(buf);
- }
- out.close();
- in.close();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (in != null)
- in.close();
- if (out != null)
- out.close();
- }
- } catch (Exception e) {
- e.printStackTrace();
- throw new Exception(e);
- }
- }
- /**
- * 圖 片上傳
- *
- * @return
- */
- public String uploadImage() throws Exception {
- log.debug("[file]--" + file);
- log.debug("[file name]--" + fileName);
- imageFileName = new Date().getTime() + getExtention(fileName);
- // 得到文件存放路徑
- log.debug("[imageFileName]--" + imageFileName);
- String dir = ServletActionContext.getServletContext().getRealPath("/UploadImages");
- File dirs = new File(dir);
- if (!dirs.exists())
- dirs.mkdir();
- // 使用原來的文件名保存圖片
- String path = dir + "/" + fileName;
- File imageFile = new File(path);
- copy(file, imageFile);
- // 縮放
- zoom(imageFile);
- // 給大圖添加文字水印
- // watermark(imageFile);
- // 給大圖添加圖片水印,可以是gif或png格式
- imageWaterMark(imageFile);
- // 創建子目錄 得到添加水印后的圖片的存儲路徑,子目錄只能一級一級的建
- String dist = dir + "/water";
- File outFile = new File(dist);
- if (!outFile.exists())
- outFile.mkdir();
- File sImgpath = new File(dist + "/" + fileName);
- // 給小圖添加文字水印
- // watermark(sImgpath);
- // 給小圖添加圖片水印,可以是gif或png格式
- imageWaterMark(sImgpath);
- // 大圖路徑
- ipath = "UploadImages/" + fileName;
- // 小圖路徑
- imgPath = "UploadImages/water/" + fileName;
- return SUCCESS;
- }
- /**
- * 縮 放處理
- *
- * @return
- */
- public void zoom(File imageFile) throws Exception {
- log.debug("[zoom][imageFile]--" + imageFile);
- try {
- // 縮略圖存放路徑
- File todir = new File(ServletActionContext.getServletContext().getRealPath("/UploadImages") + "/water");
- if (!todir.exists()) {
- todir.mkdir();
- }
- if (!imageFile.isFile())
- throw new Exception(imageFile + " is not image file error in CreateThumbnail!");
- File sImg = new File(todir, fileName);
- BufferedImage Bi = ImageIO.read(imageFile);
- // 假設圖片寬 高 最大為130 80,使用默認縮略算法
- Image Itemp = Bi.getScaledInstance(130, 80, Bi.SCALE_DEFAULT);
- double Ratio = 0.0;
- if ((Bi.getHeight() > 130) || (Bi.getWidth() > 80)) {
- if (Bi.getHeight() > Bi.getWidth())
- Ratio = 80.0 / Bi.getHeight();
- else
- Ratio = 130.0 / Bi.getWidth();
- AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(Ratio, Ratio), null);
- Itemp = op.filter(Bi, null);
- }
- ImageIO.write((BufferedImage) Itemp, "jpg", sImg);
- } catch (IOException e) {
- e.printStackTrace();
- throw new Exception(e);
- }
- }
- /**
- * 添 加文字水印
- *
- * @return
- * @throws Exception
- * @throws Exception
- */
- public void watermark(File img) throws Exception {
- log.debug("[watermark file name]--" + img.getPath());
- try {
- if (!img.exists()) {
- throw new IllegalArgumentException("file not found!");
- }
- log.debug("[watermark][img]--" + img);
- // 創建一個FileInputStream對象從源圖片獲取數據流
- FileInputStream sFile = new FileInputStream(img);
- // 創建一個Image對象并以源圖片數據流填充
- Image src = ImageIO.read(sFile);
- // 得到源圖寬
- int width = src.getWidth(null);
- // 得到源圖長
- int height = src.getHeight(null);
- // 創建一個BufferedImage來作為圖像操作容器
- BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
- // 創建一個繪圖環境來進行繪制圖象
- Graphics2D g = image.createGraphics();
- // 將原圖像數據流載入這個BufferedImage
- log.debug("width:" + width + " height:" + height);
- g.drawImage(src, 0, 0, width, height, null);
- // 設定文本字體
- g.setFont(new Font("宋體", Font.BOLD, 28));
- String rand = TEXT_TITLE;
- // 設定文本顏色
- g.setColor(Color.blue);
- // 設置透明度
- g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f));
- // 向BufferedImage寫入文本字符,水印在圖片上的坐標
- g.drawString(rand, width - (width - 20), height - (height - 60));
- // 使更改生效
- g.dispose();
- // 創建輸出文件流
- FileOutputStream outi = new FileOutputStream(img);
- // 創建JPEG編碼對象
- JPEGImageEncoder encodera = JPEGCodec.createJPEGEncoder(outi);
- // 對這個BufferedImage (image)進行JPEG編碼
- encodera.encode(image);
- // 關閉輸出文件流
- outi.close();
- sFile.close();
- } catch (IOException e) {
- e.printStackTrace();
- throw new Exception(e);
- }
- }
- /**
- * 添 加圖片水印
- *
- */
- public void imageWaterMark(File imgFile) throws Exception {
- try {
- // 目標文件
- Image src = ImageIO.read(imgFile);
- int wideth = src.getWidth(null);
- int height = src.getHeight(null);
- BufferedImage image = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB);
- Graphics2D g = image.createGraphics();
- g.drawImage(src, 0, 0, wideth, height, null);
- // 水印文件 路徑
- String waterImgPath = ServletActionContext.getServletContext().getRealPath("/UploadImages")+"/"+WATER_IMG_NAME;
- File waterFile = new File(waterImgPath);
- Image waterImg = ImageIO.read(waterFile);
- int w_wideth = waterImg.getWidth(null);
- int w_height = waterImg.getHeight(null);
- g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f));
- g.drawImage(waterImg, (wideth - w_wideth) / 2, (height - w_height) / 2, w_wideth, w_height, null);
- // 水印文件結束
- g.dispose();
- FileOutputStream out = new FileOutputStream(imgFile);
- JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
- encoder.encode(image);
- out.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public void setFile(File file) {
- this.file = file;
- }
- public String getIpath() {
- return ipath;
- }
- public void setFileFileName(String fileName) {
- this.fileName = fileName;
- }
- public void setImageFileName(String imageFileName) {
- this.imageFileName = imageFileName;
- }
- public String getJson() {
- return json;
- }
- public void setFileContentType(String fileContentType) {
- this.contentType = fileContentType;
- }
- public String getImgPath() {
- return imgPath;
- }
- }
3、struts.xml配置文件
Xml代碼
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "struts-2.0.dtd" >
- <struts>
- <include file="struts-default.xml" />
- <constant name="struts.objectFactory" value="spring" />
- <constant name="struts.devMode" value="false" />
- <constant name="struts.locale" value="zh_CN" />
- <constant name="struts.multipart.maxSize" value="10000000000000" />
- <constant name="struts.i18n.encoding" value="utf-8" />
- <package name="test" extends="struts-default">
- <interceptors>
- <interceptor-stack name="commonsStack">
- <interceptor-ref name="exception"></interceptor-ref>
- <interceptor-ref name="prepare" />
- <interceptor-ref name="params" />
- <interceptor-ref name="validation" />
- <interceptor-ref name="workflow" />
- </interceptor-stack>
- <interceptor-stack name="uploadStack">
- <interceptor-ref name="fileUpload">
- <!-- 配置允許上傳的文件類型 -->
- <param name="allowedTypes">
- image/bmp,image/png,image/gif,image/jpeg,image/jpg
- </param>
- <!-- 配置允許上傳的文件大小 -->
- <param name="maximumSize">50485760</param>
- <!-- 50M=50*1024*1024 byte-->
- </interceptor-ref>
- <interceptor-ref name="commonsStack" />
- </interceptor-stack>
- </interceptors>
- <!-- 默認攔截器 -->
- <default-interceptor-ref name="commonsStack" />
- </package>
- <package name="image" extends="test">
- <action name="image" class="imageAction">
- <interceptor-ref name="uploadStack"></interceptor-ref>
- <result name="input">/image.jsp</result>
- <result name="success">/image.jsp</result>
- </action>
- </package>
- </struts>
4、spring的配置比較簡單就不貼了,在<beans>里加入一個bean就可以了。
以上完畢!