`

struts2实现上传文件、生成缩略图、添加文字和图片水印

阅读更多

1、页面代码

代码:
<%@ 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>
action代码
代码:
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; 
    } 
 
}
struts.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就可以了。

以上完毕! <!-- / message --><!-- sig -->
分享到:
评论

相关推荐

    struts2上传文件、生成缩略图、添加文字和图片水印

    以上就是关于"Struts2上传文件、生成缩略图、添加文字和图片水印"的主要知识点,理解并掌握这些技术可以帮助开发者实现高效、安全的图片处理功能。在实际项目中,应根据具体需求灵活运用,并不断优化以提高用户体验...

    Struts实现图片上传

    此外,根据需求,可能还需要实现图片的缩略图生成、水印添加等功能。 以上就是使用Struts框架实现图片上传的基本流程和关键知识点。通过这个功能,开发者可以为用户提供便捷的图片上传体验,同时保证应用的安全性和...

    JspRun!社区论坛系统 v6.0 bulid 090423 GBK 源码版.rar

    13、修复了上传图片时如果图片是动画为该图片生成缩略图和水印图片 14、修复了在gbk项目下无法保存ftp密码的问题 15、修复了合并用户时合并短消息异常 16、修复了主题自动关闭后仍可以回复的问题 17、修复了编辑...

    JspRun!社区论坛系统 v6.0 bulid 090424 GBK 安装版.rar

    13、修复了上传图片时如果图片是动画为该图片生成缩略图和水印图片 14、修复了在gbk项目下无法保存ftp密码的问题 15、修复了合并用户时合并短消息异常 16、修复了主题自动关闭后仍可以回复的问题 17、修复了编辑...

    基于MATLAB GUI与CNN的模糊车牌识别系统:从图像预处理到字符识别全流程解析

    内容概要:本文详细介绍了基于MATLAB GUI界面和卷积神经网络(CNN)的模糊车牌识别系统。该系统旨在解决现实中车牌因模糊不清导致识别困难的问题。文中阐述了整个流程的关键步骤,包括图像的模糊还原、灰度化、阈值化、边缘检测、孔洞填充、形态学操作、滤波操作、车牌定位、字符分割以及最终的字符识别。通过使用维纳滤波或最小二乘法约束滤波进行模糊还原,再利用CNN的强大特征提取能力完成字符分类。此外,还特别强调了MATLAB GUI界面的设计,使得用户能直观便捷地操作整个系统。 适合人群:对图像处理和深度学习感兴趣的科研人员、高校学生及从事相关领域的工程师。 使用场景及目标:适用于交通管理、智能停车场等领域,用于提升车牌识别的准确性和效率,特别是在面对模糊车牌时的表现。 其他说明:文中提供了部分关键代码片段作为参考,并对实验结果进行了详细的分析,展示了系统在不同环境下的表现情况及其潜在的应用前景。

    嵌入式八股文面试题库资料知识宝典-计算机专业试题.zip

    嵌入式八股文面试题库资料知识宝典-计算机专业试题.zip

    嵌入式八股文面试题库资料知识宝典-C and C++ normal interview_3.zip

    嵌入式八股文面试题库资料知识宝典-C and C++ normal interview_3.zip

    开关磁阻电机技术参数与建模技术深度解析:4kW电机性能详述

    内容概要:本文深入探讨了一款额定功率为4kW的开关磁阻电机,详细介绍了其性能参数如额定功率、转速、效率、输出转矩和脉动率等。同时,文章还展示了利用RMxprt、Maxwell 2D和3D模型对该电机进行仿真的方法和技术,通过外电路分析进一步研究其电气性能和动态响应特性。最后,文章提供了基于RMxprt模型的MATLAB仿真代码示例,帮助读者理解电机的工作原理及其性能特点。 适合人群:从事电机设计、工业自动化领域的工程师和技术人员,尤其是对开关磁阻电机感兴趣的科研工作者。 使用场景及目标:适用于希望深入了解开关磁阻电机特性和建模技术的研究人员,在新产品开发或现有产品改进时作为参考资料。 其他说明:文中提供的代码示例仅用于演示目的,实际操作时需根据所用软件的具体情况进行适当修改。

    少儿编程scratch项目源代码文件案例素材-剑客冲刺.zip

    少儿编程scratch项目源代码文件案例素材-剑客冲刺.zip

    少儿编程scratch项目源代码文件案例素材-几何冲刺 转瞬即逝.zip

    少儿编程scratch项目源代码文件案例素材-几何冲刺 转瞬即逝.zip

    四象限直流电机速度驱动控制系统PID控制仿真模型设计与实现

    内容概要:本文详细介绍了基于PID控制器的四象限直流电机速度驱动控制系统仿真模型及其永磁直流电机(PMDC)转速控制模型。首先阐述了PID控制器的工作原理,即通过对系统误差的比例、积分和微分运算来调整电机的驱动信号,从而实现转速的精确控制。接着讨论了如何利用PID控制器使有刷PMDC电机在四个象限中精确跟踪参考速度,并展示了仿真模型在应对快速负载扰动时的有效性和稳定性。最后,提供了Simulink仿真模型和详细的Word模型说明文档,帮助读者理解和调整PID控制器参数,以达到最佳控制效果。 适合人群:从事电力电子与电机控制领域的研究人员和技术人员,尤其是对四象限直流电机速度驱动控制系统感兴趣的读者。 使用场景及目标:适用于需要深入了解和掌握四象限直流电机速度驱动控制系统设计与实现的研究人员和技术人员。目标是在实际项目中能够运用PID控制器实现电机转速的精确控制,并提高系统的稳定性和抗干扰能力。 其他说明:文中引用了多篇相关领域的权威文献,确保了理论依据的可靠性和实用性。此外,提供的Simulink模型和Word文档有助于读者更好地理解和实践所介绍的内容。

    嵌入式八股文面试题库资料知识宝典-2013年海康威视校园招聘嵌入式开发笔试题.zip

    嵌入式八股文面试题库资料知识宝典-2013年海康威视校园招聘嵌入式开发笔试题.zip

    少儿编程scratch项目源代码文件案例素材-驾驶通关.zip

    少儿编程scratch项目源代码文件案例素材-驾驶通关.zip

    小区开放对周边道路通行能力影响的研究.pdf

    小区开放对周边道路通行能力影响的研究.pdf

    冷链物流路径优化:基于NSGA-2遗传算法与软硬时间窗策略的研究

    内容概要:本文探讨了冷链物流车辆路径优化问题,特别是如何通过NSGA-2遗传算法和软硬时间窗策略来实现高效、环保和高客户满意度的路径规划。文中介绍了冷链物流的特点及其重要性,提出了软时间窗概念,允许一定的配送时间弹性,同时考虑碳排放成本,以达到绿色物流的目的。此外,还讨论了如何将客户满意度作为路径优化的重要评价标准之一。最后,通过一段简化的Python代码展示了遗传算法的应用。 适合人群:从事物流管理、冷链物流运营的专业人士,以及对遗传算法和路径优化感兴趣的科研人员和技术开发者。 使用场景及目标:适用于冷链物流企业,旨在优化配送路线,降低运营成本,减少碳排放,提升客户满意度。目标是帮助企业实现绿色、高效的物流配送系统。 其他说明:文中提供的代码仅为示意,实际应用需根据具体情况调整参数设置和模型构建。

    少儿编程scratch项目源代码文件案例素材-恐怖矿井.zip

    少儿编程scratch项目源代码文件案例素材-恐怖矿井.zip

    基于STM32F030的无刷电机高压FOC控制方案:滑膜无感FOC技术及保护机制

    内容概要:本文详细介绍了基于STM32F030的无刷电机控制方案,重点在于高压FOC(磁场定向控制)技术和滑膜无感FOC的应用。该方案实现了过载、过欠压、堵转等多种保护机制,并提供了完整的源码、原理图和PCB设计。文中展示了关键代码片段,如滑膜观测器和电流环处理,以及保护机制的具体实现方法。此外,还提到了方案的移植要点和实际测试效果,确保系统的稳定性和高效性。 适合人群:嵌入式系统开发者、电机控制系统工程师、硬件工程师。 使用场景及目标:适用于需要高性能无刷电机控制的应用场景,如工业自动化设备、无人机、电动工具等。目标是提供一种成熟的、经过验证的无刷电机控制方案,帮助开发者快速实现并优化电机控制性能。 其他说明:提供的资料包括详细的原理图、PCB设计文件、源码及测试视频,方便开发者进行学习和应用。

    基于有限体积法Godunov格式的管道泄漏检测模型研究.pdf

    基于有限体积法Godunov格式的管道泄漏检测模型研究.pdf

    嵌入式八股文面试题库资料知识宝典-CC++笔试题-深圳有为(2019.2.28)1.zip

    嵌入式八股文面试题库资料知识宝典-CC++笔试题-深圳有为(2019.2.28)1.zip

    少儿编程scratch项目源代码文件案例素材-几何冲刺 V1.5.zip

    少儿编程scratch项目源代码文件案例素材-几何冲刺 V1.5.zip

Global site tag (gtag.js) - Google Analytics