1.编写工具类
package com.test;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
* 水印处理工具
* @author visy.wang
* @date 2021/10/20 11:40
*/
public class WatermarkUtil {
/**
* 添加文字水印
* @param srcFile 源文件
* @param text 添加的文本内容
* @param font 文本字体
* @param color 文本颜色
* @throws IOException
*/
public static void addTextWatermark(File srcFile, String text, Font font, Color color) throws IOException {
//文件转图片
Image image = ImageIO.read(srcFile);
//获取图片尺寸
int width = image.getWidth(null), height = image.getHeight(null);
//创建空的画布
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//创建画笔
Graphics2D g = bufferedImage.createGraphics();
//把图片画在画布上, x和y是开始画的位置,这里是左上角(0,0)
g.drawImage(image, 0, 0, width, height, null);
//设置水印字体和颜色
g.setFont(font);
g.setColor(color);
//设置透明度
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f));
//计算水印位置-右下角:英文
//int h = height-font.getSize(), w = width-text.length()*font.getSize()/2-10;
//计算水印位置-右下角:中文
int h = height-font.getSize(), w = width-text.length()*font.getSize()-10;
//画水印
g.drawString(text, w, h);
//释放资源
g.dispose();
String fileFullName = srcFile.getName();
int splitIndex = fileFullName.lastIndexOf(".");
String fileName = fileFullName.substring(0, splitIndex);
String extName = fileFullName.substring(splitIndex + 1);
//写入本地磁盘, 使用时按具体情况处理
ImageIO.write(bufferedImage, extName, new File("D:\\test\\"+fileName+"_watermark."+extName));
}
}
2.测试
public static void main(String[] args) throws IOException{
File file = new File("D:\\test\\src.jpg");
WatermarkUtil.addTextWatermark(file, "我是水印", new Font("黑体", 0, 20), new Color(248,0,0));
}
3.添加效果