使用Java为图片添加水印
使用Java为图片添加水印
杨润康Bla 发表于2年前
使用Java为图片添加水印
  • 发表于 2年前
  • 阅读 5
  • 收藏 0
  • 点赞 2
  • 评论 0

腾讯云 技术升级10大核心产品年终让利>>>   

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

效果图
这里写图片描述

共有 人打赏支持
粉丝 15
博文 76
码字总数 0
×
杨润康Bla
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: