需要注意几个踩坑的地方(代码51行,部署在Linux 必须有这个字体,当时踩坑了,代码72注意输出图片的格式)
package com.example.Watermark;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
* @Cimpany yuJ.wang
* @ClassName: PictureUtils
* @Description: 图片添加水印
* @Date: 2023/3/13 13:48
* @Author: 老王头
*/
public class PictureUtils {
//水印字体大小
public static final int FONT_SIZE = 18;
//水印间隔
private static final int X_MOVE = 40;
private static final int Y_MOVE = 40;
/**
* @Description: 图片添加文字水印
* * @Param filePath: 图片路径
* @Param watermark: 水印文字
* @Param newFilePath: 保存路径
* @Param opacity: 透明度设置
* @Param size: 字体大小
* @Param angle: 旋转度
* @return: void
* @Author: laoWangTou
* @Date: 2023/3/13
*/
public static void watermark(String filePath,String watermark,String newFilePath,float opacity,int size,int angle) throws IOException{
// 读取原图片
File file = new File(filePath);
BufferedImage image = ImageIO.read(file);
int width = image.getWidth();
int height = image.getHeight();
// 创建Buffer缓存对象 在缓存中操作
BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 获取画笔
Graphics2D g = newImage.createGraphics();
// 将原图片绘制到缓存图片上
g.drawImage(image, 0, 0, width, height, null);
// 设置水印的字体样式 (要注意, 部署在Linux 必须有这个字体,当时踩坑了)
g.setFont(new Font("宋体", Font.BOLD, size));
// 水印颜色
g.setColor(Color.red);
g.rotate(Math.toRadians(angle), width / 2, height / 2);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, opacity));
int x = -width / 2;
int y = -height / 2;
int markWidth = FONT_SIZE * getTextLength(watermark);
int markHeight = FONT_SIZE;
while (x < width * 1.5) {
y = -height / 2;
while (y < height * 1.5) {
g.drawString(watermark, x, y);
y += markHeight + Y_MOVE;
}
x += markWidth + X_MOVE;
}
// 释放资源
g.dispose();
// 保存带水印的图片
try {
ImageIO.write(newImage, "jpg", new File(newFilePath));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @Description: 获取text的文本长度
* * @Param text:
* @return: int
* @Author: laoWangTou
* @Date: 2023/3/13
*/
private static int getTextLength(String text) {
int length = text.length();
for (int i = 0; i < text.length(); i++) {
String s = String.valueOf(text.charAt(i));
if (s.getBytes().length > 1) {
length++;
}
}
length = length % 2 == 0 ? length / 2 : length / 2 + 1;
return length;
}
public static void main(String[] args) throws IOException {
watermark("D:\\test\\1\\3.jpg","测试水印","D:\\test\\1\\33.jpg",0.2f,20,30);
}
}