文档章节

使用Java为图片添加水印

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

首先新建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>

效果图
这里写图片描述

本文转载自:http://blog.csdn.net/yangrunkangbla/article/details/50511955

共有 人打赏支持
非著名程序员Bla
粉丝 15
博文 75
码字总数 0
作品 0
合肥
后端工程师
私信 提问
在JAVA中使用Thumbnails为图片加水印

在JAVA中使用Thumbnails为图片加水印 将D盘下面的cat.jpg作为水印加在2.jpg上面,输出新的图片2_cat.jpg到D盘下面 1、java类 1)、of(new File("D:2.jpg")) 打开一张图片作为底图 2)、size(20...

Qiu_CJ
06/26
0
0
使用 Grapicmagick 和 Im4java 处理图片

ImageMagick是个图片处理工具可以安装在绝大多数的平台上使用,Linux、Mac、Windows都没有问题。GraphicsMagick是在ImageMagick基础上的另一个项目,大大提高了图片处理的性能,在linux平台上...

voole
05/07
0
0
Java 借助ImageMagic实现图片编辑服务

Java 借助ImageMagic实现图片编辑服务 java原生对于图片的编辑处理并没有特别友好,而且问题也有不少,那么作为一个java后端,如果要提供图片的编辑服务可以怎么办?也得想办法去支持业务需求...

小灰灰Blog
04/18
0
0
PageOffice中word常用接口对象---WaterMark类

为了保护版权或辨别文件的真伪,有时需要在Word文件中添加一些文字水印,而WaterMark类就是现实了通过程序给在线编辑的Word文件添加水印这一功能,从而实现此效果。 WaterMark类所属命名空间...

山里的红杏
09/11
0
0
Thumbnailator的简介和使用范例

1.简单介绍 借用红薯对Thumbnailator 的描述:Thumbnailator是一个用来生成图像缩略图的 Java类库,通过很简单的代码即可生成图片缩略图,也可直接对一整个目录的图片生成缩略图。 有了这玩意...

JoeyBlue
2011/08/14
23.5K
17

没有更多内容

加载失败,请刷新页面

加载更多

java框架学习日志-7(静态代理和JDK代理)

静态代理 我们平时去餐厅吃饭,不是直接告诉厨师做什么菜的,而是先告诉服务员点什么菜,然后由服务员传到给厨师,相当于服务员是厨师的代理,我们通过代理让厨师炒菜,这就是代理模式。代理...

白话
44分钟前
6
0
Flink Window

1.Flink窗口 Window Assigner分配器。 窗口可以是时间驱动的(Time Window,例如:每30秒钟),也可以是数据驱动的(Count Window,例如:每一百个元素)。 一种经典的窗口分类可以分成: 翻...

满小茂
45分钟前
3
0
my.ini

1

architect刘源源
今天
6
0
docker dns

There is a opensource application that solves this issue, it's called DNS Proxy Server It's a DNS server that solves containers hostnames, if could not found a hostname that mat......

kut
今天
7
0
寻找数学的广度——《这才是数学》读书笔记2700字

寻找数学的广度——《这才是数学》读书笔记2700字: 文|程哲。数学学习方式之广:国内外数学教育方面的专家,进行了很多种不同的数学学习方式尝试,如数学绘本、数学游戏、数学实验、数学步道...

原创小博客
今天
13
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部