struts2上传文件、生成缩略图、添加文字和图片水印
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>
<%@ 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;
- }
- }
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>
<?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就可以了。
以上完毕!