1.编写工具类
package com.test;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class WatermarkUtil {
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();
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()-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.添加效果
![在这里插入图片描述](https://img-blog.csdnimg.cn/9941df0270c942b29dcc640c89fef4e6.jpg?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5rSS5LqG6ISx,size_20,color_FFFFFF,t_70,g_se,x_16#pic_center)