文档章节

使用Java为图片添加水印

杨润康Bla
 杨润康Bla
发布于 2016/05/18 18:04
字数 1502
阅读 5
收藏 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
粉丝 14
博文 76
码字总数 0
作品 0
合肥
后端工程师
使用 Grapicmagick 和 Im4java 处理图片

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

voole
05/07
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
Java 借助ImageMagic实现图片编辑服务

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

小灰灰Blog
04/18
0
0
Jmagic与 ImageMagick linux下安装与使用

公司现在用的是java开发,后台难免会用到图片上传,自动生成缩略图,然后不可避免的要安装一些比较好的软件,我们公司使用的是ImageMagick,一个图片处理程序,就是说我们可以通过程序来进行...

枫爱若雪
2012/09/21
0
0
ImageMagick for java Jmagick的使用

在做pdf文档转成jpg的时候,发现了Jmagick的创建高质量的图片的一个java类库,自己以前使用另外的一个类库,感觉这个更好点,就试着用了下,感觉不错 1.使用的windows下的jmagick-win-6.3.9-Q16...

涂孟超
2013/08/13
0
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

002,zabbix-agent的安装 监控Linux主机

2.1.安装zabbix-agent $ rpm -i http://repo.zabbix.com/zabbix/3.4/rhel/7/x86_64/zabbix-release-3.4-2.el7.noarch.rpm$ yum install -y zabbix-agent zabbix-get 2.2.配置zabbix-agent ......

happyeveryday32
31分钟前
2
0
docker learn :swarm

swarm是什么 swarm是一组运行docker服务的集群,之后,还是使用那些命令去操作docker,但是是通过swarm manager来执行的。 swarm中的机器可以是实体的也可以是虚拟的,加入swarm后,他们被当作...

writeademo
31分钟前
1
0
Golang + vscode 开发环境配置

GOPATH 环境变量的配置 https://my.oschina.net/xinxingegeya/blog/718305 安装vscode go 扩展 下载vscode ,安装go的扩展https://github.com/Microsoft/vscode-go 该扩展对 Golang 支持非常......

秋风醉了
34分钟前
0
0
idea jar包

我自己用idea新建一个springboot项目,打包一直有问题,百度了下,又总结了下。 方式一: 找到Project Structure菜单,然后点开,照下图点击 然后出现下图所示 红框1:为你项目的main函数所在...

朝如青丝暮成雪
35分钟前
0
0
Vue scoped CSS 与深度作用选择器 /deep/

使用 scoped 后,父组件的样式将不会渗透到子组件中。 例如(无效): <template> <div id="app"> <el-input class="text-box" v-model="text"></el-input> </div></template><......

不负好时光
35分钟前
0
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部