zoukankan      html  css  js  c++  java
  • 图片水印

    谁用maven工程来开发,并且是用struts框架,算是用来回忆一下struts的使用

    水印接口类,定义一些属性和加水印的方法

    WterMark.java

    package youth.hong.watermark;
    
    import java.awt.Color;
    import java.awt.Font;
    import java.io.File;
    
    public interface WaterMark {
        
        public static final int X = 300;
        
        public static final int Y = 300;
        
        public static final int FONT_STYLE = Font.BOLD;
        
        public static final Color FONT_COLOR = Color.BLACK;
        
        public static final int FONT_SIZE = 50;
        
        public static final String MARK_TEXT = "谢谢慕课";
        
        public static final String FONT_NAME = "微软雅黑";
        
        public static final float ALPHA = 0.3f;
        
        public static final String IMAGE_WATER = "blue015.png";
        
        public String watermark(File file, String uploadPath, String realUploadPath, String fileFileName,
                String fileContextType);
        
        
    }

    文字水印

    FontWaterMark.java

    package youth.hong.watermark;
    
    import java.awt.AlphaComposite;
    import java.awt.Font;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    
    import javax.imageio.ImageIO;
    
    public class FontWaterMark implements WaterMark {
    
        @Override
        public String watermark(File file, String uploadPath, String realUploadPath, String fileFileName,
                String fileContextType) {
    
            OutputStream out = null;
    
            try {
                out = new FileOutputStream(realUploadPath + "/font_" + fileFileName);
                Image image = ImageIO.read(file);
                int width = image.getWidth(null);
                int height = image.getHeight(null);
                BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                Graphics2D g = bi.createGraphics();
                g.drawImage(image, 0, 0, width, height, null);
                g.setFont(new Font(FONT_NAME, FONT_STYLE, FONT_SIZE));
                g.setColor(FONT_COLOR);
                int textWidth = this.getTextLength(MARK_TEXT);
                int textHeight = FONT_SIZE;
                int widthOff = width - textWidth;
                int heightOff = height - textHeight;
                int x = X;
                int y = Y;
    
                if (x > widthOff) {
                    x = widthOff;
                }
    
                if (y > heightOff) {
                    y = heightOff;
                }
                g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA));
    
                g.drawString(MARK_TEXT, x, y + FONT_SIZE);
    
                g.dispose();
    
                ImageIO.write(bi, fileFileName.substring(fileFileName.indexOf('.') + 1), out);
    
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    
            return uploadPath + "/font_" + fileFileName;
        }
    
        public int getTextLength(String text) {
            int length = 0;
            // 存储文字的像素长度,中文字是英文字母的两倍宽度,取其宽度是为了防止它超出图片的范围
            int pixValue = 0;
            for (int i = 0; i < text.length(); i++) {
    
                length = String.valueOf(text.getBytes()).length();
    
                if (length > 1) {
                    pixValue += FONT_SIZE;
                } else {
                    pixValue += FONT_SIZE / 2;
                }
            }
    
            return pixValue;
        }
    
    }

    图片水印

    package youth.hong.watermark;
    
    import java.awt.AlphaComposite;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    
    import javax.imageio.ImageIO;
    
    public class ImageWaterMark implements WaterMark {
    
        @Override
        public String watermark(File file, String uploadPath, String realUploadPath, String fileFileName,
                String fileContextType) {
    
            OutputStream out = null;
            File f = new File(realUploadPath + "/" + IMAGE_WATER);
            
            System.out.println(f);
    
            try {
                out = new FileOutputStream(realUploadPath + "/image_" + fileFileName);
                Image image = ImageIO.read(file);
                Image imageWater = ImageIO.read(f);
                int width = image.getWidth(null);
                int height = image.getHeight(null);
                BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                Graphics2D g = bi.createGraphics();
                g.drawImage(image, 0, 0, width, height, null);
                
                int imageWidth = imageWater.getWidth(null);
                int imageHeight = imageWater.getHeight(null);
                int widthOff = width - imageWidth;
                int heightOff = height - imageHeight;
                int x = X;
                int y = Y;
    
                if (x > widthOff) {
                    x = widthOff;
                }
    
                if (y > heightOff) {
                    y = heightOff;
                }
                g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.7f));
    
                g.drawImage(imageWater, x, y, null);
    
                g.dispose();
    
                ImageIO.write(bi, fileFileName.substring(fileFileName.indexOf('.') + 1), out);
    
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    
            return uploadPath + "/image_" + fileFileName;
        }
    
        
    
    }

    多文字水印

    package youth.hong.watermark;
    
    import java.awt.AlphaComposite;
    import java.awt.Font;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    
    import javax.imageio.ImageIO;
    
    public class MoreFontWaterMark implements WaterMark {
    
        @Override
        public String watermark(File file, String uploadPath, String realUploadPath, String fileFileName,
                String fileContextType) {
    
            OutputStream out = null;
    
            try {
                out = new FileOutputStream(realUploadPath + "/font_" + fileFileName);
                Image image = ImageIO.read(file);
                int width = image.getWidth(null);
                int height = image.getHeight(null);
                BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                Graphics2D g = bi.createGraphics();
                g.drawImage(image, 0, 0, width, height, null);
                g.setFont(new Font(FONT_NAME, FONT_STYLE, FONT_SIZE));
                g.setColor(FONT_COLOR);
                
                g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA));
    
                //倾斜画布,以画布的中心点倾斜30°
                g.rotate(Math.toRadians(30), bi.getWidth() / 2, bi.getHeight() / 2);
                
                int textWidth = this.getTextLength(MARK_TEXT);
                
                int x = -width / 2;
                while(x < width * 2) {
                    
                    
                    int y = -height / 2;
                    
                    while(y < height * 2) {
                        g.drawString(MARK_TEXT, x, y);
                        
                        y += 100;
                    }
                    
                    x = x + 100 + textWidth;
                }
                
    
                g.dispose();
    
                ImageIO.write(bi, fileFileName.substring(fileFileName.indexOf('.') + 1), out);
    
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    
            return uploadPath + "/font_" + fileFileName;
        }
    
        public int getTextLength(String text) {
            int length = 0;
            // 存储文字的像素长度
            int pixValue = 0;
            for (int i = 0; i < text.length(); i++) {
    
                length = String.valueOf(text.getBytes()).length();
    
                if (length > 1) {
                    pixValue += FONT_SIZE;
                } else {
                    pixValue += FONT_SIZE / 2;
                }
            }
    
            return pixValue;
        }
    
    
    }

    多图片水印

    package youth.hong.watermark;
    
    import java.awt.AlphaComposite;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    
    import javax.imageio.ImageIO;
    
    public class MoreImageWaterMark implements WaterMark {
    
        @Override
        public String watermark(File file, String uploadPath, String realUploadPath, String fileFileName,
                String fileContextType) {
    
            OutputStream out = null;
            File f = new File(realUploadPath + "/" + IMAGE_WATER);
    
            try {
                out = new FileOutputStream(realUploadPath + "/moreImage_" + fileFileName);
                Image image = ImageIO.read(file);
                Image imageWater = ImageIO.read(f);
                int width = image.getWidth(null);
                int height = image.getHeight(null);
                BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                Graphics2D g = bi.createGraphics();
                g.drawImage(image, 0, 0, width, height, null);
                g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA));
    
                //倾斜画布,以画布的中心点倾斜30°
                g.rotate(Math.toRadians(30), bi.getWidth() / 2, bi.getHeight() / 2);
                
                int imageWidth = imageWater.getWidth(null);
                int imageHeight = imageWater.getHeight(null);
                
                
                int x = -width / 2;
                while(x < width * 2) {
                    
                    
                    int y = -height / 2;
                    
                    while(y < height * 2) {
                        g.drawImage(imageWater, x, y, null);
                        
                        y += 100 + imageHeight;
                    }
                    
                    x = x + 100 + imageWidth;
                }
                
    
                g.dispose();
    
                ImageIO.write(bi, fileFileName.substring(fileFileName.indexOf('.') + 1), out);
    
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    
            return uploadPath + "/moreImage_" + fileFileName;
        }
    
    }

    上传服务类

    package youth.hong.watermark;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    
    public class UploadService {
    
        public String upload(File file, String uploadPath, String realUploadPath, String fileFileName,
                String fileContextType) {
    
            InputStream in = null;
    
            OutputStream out = null;
    
            try {
                in = new FileInputStream(file);
                out = new FileOutputStream(realUploadPath + "/" + fileFileName);
                byte[] buff = new byte[1024];
    
                while ((in.read(buff)) > 0) {
                    out.write(buff);
                }
    
            } catch (Exception e) {
                System.out.println("请求的操作无法在使用用户映射区域打开的文件上执行。");
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
            return uploadPath + "/" + fileFileName;
        }
    
    }

    action

    package youth.hong.watermark;
    
    import java.io.File;
    import java.util.ArrayList;
    import java.util.List;
    
    import org.apache.struts2.ServletActionContext;
    
    import com.opensymphony.xwork2.ActionSupport;
    
    public class WaterMarkAction extends ActionSupport {
    
        private static final long serialVersionUID = 1L;
    
        private List<File> file;
        private List<String> fileContentType;
        private List<String> fileFileName;
        private List<String> srcs;
    
        public List<String> getSrcs() {
            return srcs;
        }
    
        public void setSrcs(List<String> srcs) {
            this.srcs = srcs;
        }
    
        @Override
        public String execute() throws Exception {
            dealWithFiles();
            return SUCCESS;
        }
    
        public String upload() {
            return "upload";
        }
    
        public List<File> getFile() {
            return file;
        }
    
        public void setFile(List<File> file) {
            this.file = file;
        }
    
        public List<String> getFileContentType() {
            return fileContentType;
        }
    
        public void setFileContentType(List<String> fileContentType) {
            this.fileContentType = fileContentType;
        }
    
        public List<String> getFileFileName() {
            return fileFileName;
        }
    
        public void setFileFileName(List<String> fileFileName) {
            this.fileFileName = fileFileName;
        }
    
        public void dealWithFiles() {
            List<String> imageSrcs = new ArrayList<String>();
    //        UploadService us = new UploadService();
            WaterMark wm = new MoreImageWaterMark();
    
    
            String uploadPath = "/images";
            String realUploadPath = ServletActionContext.getServletContext().getRealPath("/images");
            System.out.println(realUploadPath);
            for (int i = 0; i < file.size(); i++) {
                // String imageSrc = us.upload(file.get(i), uploadPath,
                // realUploadPath, fileFileName.get(i), fileContentType.get(i));
                // String imageSrc = fwm.watermark(file.get(i), uploadPath,
                // realUploadPath, fileFileName.get(i), fileContentType.get(i));
                String imageSrc = wm.watermark(file.get(i), uploadPath, realUploadPath, fileFileName.get(i),
                        fileContentType.get(i));
                imageSrcs.add(imageSrc);
                System.out.println(imageSrc);
            }
            this.setSrcs(imageSrcs);
    
        }
    
    }

    struts.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">
    
    <struts>
    
        <constant name="struts.enable.DynamicMethodInvocation" value="true" />
        <constant name="struts.devMode" value="true" />
         <constant name="struts.multipart.saveDir" value="/image" />
         <constant name="struts.multipart.maxSize" value="2097152" />
        
        <package name="default" namespace="/" extends="struts-default">
    
            <action name="watermark" class="youth.hong.watermark.WaterMarkAction">
                <result>
                    /index.jsp
                </result>
                
                <result name="upload">
                    /watermark.jsp
                </result>
            </action>
        </package>
    
    </struts>

    web.xml

    <!DOCTYPE web-app PUBLIC
     "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
     "http://java.sun.com/dtd/web-app_2_3.dtd" >
    
    <web-app>
        <display-name>Archetype Created Web Application</display-name>
    
        <filter>
            <filter-name>struts2</filter-name>
            <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
        </filter>
    
        <filter-mapping>
            <filter-name>struts2</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    
    </web-app>

    pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <parent>
            <groupId>youth.hong.watermark</groupId>
            <artifactId>watermark-parent</artifactId>
            <version>0.0.1-SNAPSHOT</version>
            <!-- 如果install了那么可以不写也找的到 -->
            <relativePath>../watermark-parent/pom.xml</relativePath>
        </parent>
    
        <artifactId>watermark-main</artifactId>
        <packaging>war</packaging>
        <name>watermark-main Maven Webapp</name>
        <url>http://maven.apache.org</url>
        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
            </dependency>
    
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.apache.struts</groupId>
                <artifactId>struts2-core</artifactId>
            </dependency>
            <dependency>
                <groupId>jstl</groupId>
                <artifactId>jstl</artifactId>
            </dependency>
    
            <dependency>
                <groupId>taglibs</groupId>
                <artifactId>standard</artifactId>
            </dependency>
    
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.eclipse.jetty</groupId>
                    <artifactId>jetty-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>

    index.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib prefix="s" uri="/struts-tags"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <%
        String path = request.getServletPath();
    %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    esrfgdfbdfgb
        <s:iterator value="srcs" var="src">
            <img  alt="图片加载失败!" src='<s:property value="#src"/>' />
    
        </s:iterator>
        
    
    
    
    
    </body>
    </html>

    watermark.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    
    <form action="<%=request.getServletPath() %>/watermark!execute" method="post" enctype="multipart/form-data">
        <input type="file" name="file" /><br />
        <input type="file" name="file" /><br />
        <input type="file" name="file" /><br />
        <input type="file" name="file" /><br />
        <input type="file" name="file" /><br />
        <input  type="submit" value="submit" />
        
        
    </form>
    
    </body>
    </html>
  • 相关阅读:
    《数据密集型应用系统设计》读书笔记
    每周总结
    每周总结
    每周总结
    《数据密集型应用系统设计》读书笔记
    每周总结
    《重构》读书笔记
    每周总结
    软件过程与管理知识回顾
    操作系统知识汇总5-6章
  • 原文地址:https://www.cnblogs.com/honger/p/5847701.html
Copyright © 2011-2022 走看看