源码如下:
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;/*** 图片添加文字水印** @param sourceImagePath 原图路径* @param targetImagePath 加水印后图片的保存路径* @param watermarkText 水印文字*/
public static String addWatermark(String sourceImagePath, String targetImagePath, String watermarkText) {if (sourceImagePath == null || targetImagePath == null || watermarkText == null) {log.error("【FileUtils.addWatermark】参数不能为空");return sourceImagePath;}if (watermarkText.isEmpty() || watermarkText.length() > 50) {log.error("【FileUtils.addWatermark】水印文字不能为空且长度不能超过50个字符");return sourceImagePath;}File sourceFile = new File(sourceImagePath);File targetFile = new File(targetImagePath);if (!sourceFile.exists() || !sourceFile.isFile()) {log.error("【FileUtils.addWatermark】源文件不存在或路径错误");return sourceImagePath;}try {BufferedImage originalImage = ImageIO.read(sourceFile);BufferedImage watermarkedImage = ImageUtils.applyTextWatermark(originalImage, watermarkText);File parentDir = targetFile.getParentFile();if (!parentDir.exists()) {parentDir.mkdirs();}ImageIO.write(watermarkedImage, "png", targetFile);log.info("【FileUtils.addWatermark】添加水印成功,已保存至: " + targetImagePath);} catch (IOException | FontFormatException e) {log.error("【FileUtils.addWatermark】添加水印失败", e);}return targetImagePath;
}/*** 应用文字水印到图片上** @param image 原始图片* @param text 水印文字* @return 加了水印的图片* @throws IOException 图像处理异常*/
private static BufferedImage applyTextWatermark(BufferedImage image, String text) throws IOException, FontFormatException {// 创建图形上下文Graphics2D g2d = image.createGraphics();g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f)); // 透明度//读取宋体字体文件Font font = Font.createFont(Font.TRUETYPE_FONT, Objects.requireNonNull(ImageUtils.class.getResourceAsStream("/fonts/simsun.ttc")));// 设置水印文本的字体和颜色g2d.setFont(font.deriveFont(Font.PLAIN, 30)); // 设置中文字体,确保字体支持中文g2d.setColor(Color.BLACK);// 获取文本的宽度和高度,以便正确放置水印FontMetrics metrics = g2d.getFontMetrics();int textWidth = metrics.stringWidth(text);int textHeight = metrics.getHeight();// 获取图片的宽度和高度int imageWidth = image.getWidth();int imageHeight = image.getHeight();// 计算右下角的坐标int x = imageWidth - textWidth - 10; // 留一些边距int y = imageHeight - textHeight - 10; // 留一些边距// 将文本绘制到图片上String watermarkText = new String(text.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);g2d.drawString(watermarkText, x, y);// 释放图形上下文的资源g2d.dispose();return image;
}public static void main(String[] args) {addWatermark("C:\\Users\\JTDZ2PFE\\Desktop\\Son_Goku.png", "C:\\Users\\JTDZ2PFE\\Desktop\\Son_Goku1.png", "添加水印");
}
1.获取字体文件,Windows系统进入C:\WINDOWS\Fonts目录
2.选取自己需要的字体文件,拷贝到项目配置文件目录下
3.这样就避免了图片添加水印时,linux环境找不到字体而导致的乱码问题。