文档章节

使用Java为图片添加水印

非著名程序员Bla
 非著名程序员Bla
发布于 2016/05/18 18:04
字数 1502
阅读 379
收藏 0

精选30+云产品,助力企业轻松上云!>>>

首先新建Web项目,建立完成之后,新建各种文件,新建完成之后项目结构图如下所示:

这里写图片描述

ImageMarkService.java

package com.watermart;

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.OutputStream;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class ImageMarkService implements MarkService {

    @Override
    public String watermark(File image, String imageFileName,
            String uploadPath, String realUploadPath) {
        /**水印图片相关信息Start**/
        String logoFileName = "logo_"+imageFileName;
        OutputStream os = null;
        /**水印图片相关信息End**/

        //Logo的路径
        String logoPath=realUploadPath + "/" + LOGO;

        try {
            //获取传过来的图片的宽和高
            Image readImage = ImageIO.read(image);
            int width = readImage.getWidth(null);
            int height = readImage.getHeight(null);
            //1.
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            //2.
            Graphics2D g = bufferedImage.createGraphics();
            //3.
            g.drawImage(readImage, 0, 0, width, height,null);
            //4.
                //操作logo文件
            File logo = new File(logoPath);
            Image logoImage = ImageIO.read(logo);
            int logoWidth = logoImage.getWidth(null);
            int logoHeight = logoImage.getHeight(null);

            int widthDiff = width-logoWidth;
            int heightDiff = height-logoHeight;

            int x = X;
            int y = Y;

            if(x>widthDiff){
                x = widthDiff; 
            }
            if(y>heightDiff){
                y = heightDiff; 
            }
            //透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA));
            g.drawString(MARK_TEXT, x, y+FONT_SIZE);
            g.drawImage(logoImage, x, y, null);
            g.dispose();
            //5.
            os = new FileOutputStream(realUploadPath+"/"+logoFileName);
            System.out.println("添加图片水印的文件:"+realUploadPath+"/"+logoFileName);
            //6.
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
            encoder.encode(bufferedImage);
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                if(os != null){
                    os.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return uploadPath+"/"+logoFileName;
    }

}

MarkService.java

package com.watermart;

import java.awt.Color;
import java.awt.Font;
import java.io.File;

/** * Mark接口 */
public interface MarkService {
    /*一些参数的设置*/
    public static final String MARK_TEXT = "测试水印文字";//水印文字
    public static final String FONT_NAME = "微软雅黑";
    public static final int FONT_STYLE = Font.BOLD;
    public static final int FONT_SIZE = 120;
    public static final Color FONT_COLOR = Color.BLACK;
    //文字的位置
    public static final int X=10;
    public static final int Y=10;
    //水印的透明度
    public static final float ALPHA=0.3F;
    //水印图片的名称
    public static final String LOGO="logo.png";

    String watermark(File image,String imageFileName,String uploadPath,String realUploadPath);

}

PicInfo.java

package com.watermart;

/** * 图片信息 * * 封装 */
public class PicInfo {

    /** * 图片地址URL */
    private String imageURL;
    /** * 水印图片地址URL */
    private String logoImageURL;


    public String getImageURL() {
        return imageURL;
    }
    public void setImageURL(String imageURL) {
        this.imageURL = imageURL;
    }
    public String getLogoImageURL() {
        return logoImageURL;
    }
    public void setLogoImageURL(String logoImageURL) {
        this.logoImageURL = logoImageURL;
    }
}

TextMarkService.java

package com.watermart;

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.OutputStream;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class TextMarkService implements MarkService {

    @Override
    public String watermark(File image, String imageFileName,
            String uploadPath, String realUploadPath) {
        /**水印图片相关信息Start**/
        String logoFileName = "logo_"+imageFileName;
        OutputStream os = null;
        /**水印图片相关信息End**/

        try {
            //获取传过来的图片的宽和高
            Image readImage = ImageIO.read(image);
            int width = readImage.getWidth(null);
            int height = readImage.getHeight(null);
            //1.
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            //2.
            Graphics2D g = bufferedImage.createGraphics();
            //3.
            g.drawImage(readImage, 0, 0, width, height,null);
            //4.
            g.setFont(new Font(FONT_NAME,FONT_STYLE,FONT_SIZE));
            g.setColor(FONT_COLOR);

            int width1 = FONT_SIZE*getTextLength(MARK_TEXT);
            int height1=FONT_SIZE;

            int widthDiff = width-width1;
            int heightDiff = height-height1;

            int x = X;
            int y = Y;

            if(x>widthDiff){
                x = widthDiff; 
            }
            if(y>heightDiff){
                y = heightDiff; 
            }
            //透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA));
            g.drawString(MARK_TEXT, x, y+FONT_SIZE);
            g.dispose();
            //5.
            os = new FileOutputStream(realUploadPath+"/"+logoFileName);
            System.out.println("添加文字水印的文件:"+realUploadPath+"/"+logoFileName);
            //6.
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
            encoder.encode(bufferedImage);
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                if(os != null){
                    os.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return uploadPath+"/"+logoFileName;
    }

    /** * 获得文本长度值 * @param text * @return */
    public int getTextLength(String text){
        int length = text.length();
        for (int i = 0; i < length; i++) {
            String s=String.valueOf(text.charAt(i));
            //判断是中文还是英文 一个中文==2个英文
            if(s.getBytes().length>1){
                length++;
            }
        }
        length = length%2==0?length/2:length/2+1;
        return length;
    }
}

UploadService.java

package com.watermart;

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 {
    /** * 上传图片 * @param image 图片 * @param imageFileName 图片名称 * @param uploadPath 上传路径 * @param realUploadPath 上传的真实路径 存储在磁盘中的文件路径 * @return 文件路径 */
    @SuppressWarnings("unused")
    public String uploadImage(File image,String imageFileName,String uploadPath,String realUploadPath){
        //输入流
        InputStream is = null;
        //输出流
        OutputStream os = null;

        try {
            //将网页中上传的文件放进内存中,之后可以操作了
            is = new FileInputStream(image);
            //输出流
            os = new FileOutputStream(realUploadPath + "/" + imageFileName);

            System.out.println("存储文件的地方:"+realUploadPath + "/" + imageFileName);
            byte[] buffer = new byte[1024];
            int len = 0;
            while((len=is.read(buffer))>0){
                //将缓存区中的数据写出去
                os.write(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //返回文件路径
        return uploadPath + "/" + imageFileName;
    }
}

WaterMarkAction.java

package com.watermart;

import java.io.File;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class WaterMarkAction extends ActionSupport {
    private static final long serialVersionUID = 2925392814200518331L;

    private File image; //上传的文件
    private String imageFileName; //图片文件名称不能包含中文,否则会上传失败
    private String uploadPath; //上传路径

    //图片信息
    private PicInfo picInfo = new PicInfo();

    public PicInfo getPicInfo() {
        return picInfo;
    }

    public void setPicInfo(PicInfo picInfo) {
        this.picInfo = picInfo;
    }

    public String getUploadPath() {
        return uploadPath;
    }

    public void setUploadPath(String uploadPath) {
        this.uploadPath = uploadPath;
    }

    public String watermark() throws Exception{
        //获取文件上传的地址
        String realUploadPath = ServletActionContext.getServletContext().getRealPath(uploadPath);
        //构建服务类
        UploadService uploadService = new UploadService();
        //写入硬盘后,获取文件存放的位置
        String imageURL = uploadService.uploadImage(image, imageFileName, uploadPath, realUploadPath);
        //存入文件的地址,用于前台的显示
        picInfo.setImageURL(imageURL);

        MarkService markService = new ImageMarkService();
        picInfo.setLogoImageURL(markService.watermark(image, imageFileName, uploadPath, realUploadPath));
        return SUCCESS;
    }

    public File getImage() {
        return image;
    }

    public void setImage(File image) {
        this.image = image;
    }

    public String getImageFileName() {
        return imageFileName;
    }

    public void setImageFileName(String imageFileName) {
        this.imageFileName = imageFileName;
    }
}

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.devMode" value="true" />

    <!-- 配置请求后缀 -->
    <constant name="struts.action.extension" value="action" />
    <!-- 编码配置 -->
    <constant name="struts.i18n.encoding" value="UTF-8" />
    <!-- 文件上传大小配置 -->
    <constant name="struts.multipart.maxSize" value="1073741824" />
    <!-- 设置上传文件的临时文件夹 -->
    <constant name="struts.multipart.saveDir" value="/tmpUpload" />

    <package name="default" namespace="/" extends="struts-default">
        <action name="watermark" class="com.watermart.WaterMarkAction" method="watermark">
            <!-- 配置参数信息 -->
            <param name="uploadPath">/images</param>

            <result name="success">watermark.jsp</result>
        </action>
    </package>


</struts>

index.jsp

<?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.devMode" value="true" />

    <!-- 配置请求后缀 -->
    <constant name="struts.action.extension" value="action" />
    <!-- 编码配置 -->
    <constant name="struts.i18n.encoding" value="UTF-8" />
    <!-- 文件上传大小配置 -->
    <constant name="struts.multipart.maxSize" value="1073741824" />
    <!-- 设置上传文件的临时文件夹 -->
    <constant name="struts.multipart.saveDir" value="/tmpUpload" />

    <package name="default" namespace="/" extends="struts-default">
        <action name="watermark" class="com.watermart.WaterMarkAction" method="watermark">
            <!-- 配置参数信息 -->
            <param name="uploadPath">/images</param>

            <result name="success">watermark.jsp</result>
        </action>
    </package>


</struts>

watermark.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<!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>处理结果</title>
</head>
<body>
    <table width="100%" align="center" border="1">
        <tr>
            <td width="50%">
                <img src="${pageContext.request.contextPath}<s:property value="picInfo.imageURL" />">
            </td>
            <td width="50%">
                <img src="${pageContext.request.contextPath}<s:property value="picInfo.logoImageURL" />">
            </td>
        </tr>
    </table>
</body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>WaterMaker</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

   <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>

效果图
这里写图片描述

非著名程序员Bla
粉丝 15
博文 75
码字总数 0
作品 0
合肥
后端工程师
私信 提问
加载中
请先登录后再评论。
Java 添加文本水印和图片水印到 Word 文档

在日常编辑Word文档时,为了标明文档的重要性或者注明版权所有,我们通常需要给Word文档添加水印。本文将展示如何使用免费的Free Spire.Doc for Java组件为Word文档添加文本水印和图片水印。...

Jazz_z
04/08
8
0
Java添加水印到Word文档

水印是一种常用于各种文档的声明、防伪手段,一般可设置文字水印或者加载图片作为水印。以下内容将分享通过Java编程给Word文档添加水印效果的方法,即 文本水印 图片水印 使用工具:Free Sp...

E_iceblue
2019/09/11
0
0
Java 添加Word文本水印、图片水印

水印是一种常用于各种文档的声明、防伪手段,一般可设置文字水印或者加载图片作为水印。以下内容将分享通过Java编程给Word文档添加水印效果的方法,即 文本水印 图片水印 使用工具:Free Sp...

E-iceblue
2019/05/20
0
0
Java 删除/复制Word文档水印

在前文中我们介绍了在Java应用程序中给Word文档添加文本水印和图片水印的方法,这篇文章将介绍如何删除、复制水印。Free Spire.Doc for Java支持删除和复制Word文档中的文本水印和图片水印。...

osc_j7fxnjjx
06/26
7
0
Java 添加文本水印和图片水印到 Word文档

在日常编辑Word文档时,为了标明文档的重要性或者注明版权所有,我们通常需要给Word文档添加水印。本文将展示如何使用免费的Free Spire.Doc for Java组件为Word文档添加文本水印和图片水印。...

Jazzz
06/23
0
0

没有更多内容

加载失败,请刷新页面

加载更多

java使用jsoup时绕过https证书验证.md

java 代码 增加一个工具类 在jsoup获取之前调用此方法 //your codeSSLHelper.init();Connection connect = Jsoup.connect(url).userAgent(USER_AGENT);connect.header("Accept","text/htm......

MeiJM
5分钟前
4
0
6 Message 消息提示框

1 element.js导入message import { Message } from 'element-ui'# 赋值给变量,便于this调用Vue.prototype.$message = Message 2 调用 this.$message.error('错误')类型有:success,w......

书阳
6分钟前
0
0
聊聊rocketmq-client-go的strategy

序 本文主要研究一下rocketmq-client-go的strategy AllocateStrategy rocketmq-client-go-v2.0.0/consumer/strategy.go type AllocateStrategy func(string, string, []*primitive.MessageQ......

go4it
33分钟前
21
0
BuildRun低代码开发教程八节 | 图表和仪表盘展示

课程说明 ▍ 1.1 课程实现功能 本课程为物联网应用平台设计一个仪表盘首页,包括以下内容: 卡片展示设备总数; 卡片展示网关总数; 卡片展示产品总数; 卡片展示产品分组总数; 图表展示各运...

BuildRun团队
37分钟前
11
0
JavaSE第03篇:Java基础语法之运算符和流程控制

本章将会延续JavaSE第02篇,详细讲解Java基础语法中的运算符和流程控制中的顺序结构、分支结构。 第一章:运算符 运算符,简而言之就是运算的符号。 我们通常所理解的运算一般和数学有关系,...

雷哒哒
40分钟前
6
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部