问题:图片太大时存在水印文字无法铺满整张图
package test.demo;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
public class WatermarkUtil {
public static void main(String[] args) {
try {
//水印文字
String str = "测试专用其他勿扰";
// 原图片的路径
File inputImage = new File("C:\\Users\\Admin\\Desktop\\image.png");
// 输出图片的路径
File outputImage = new File("C:\\Users\\Admin\\Desktop\\image_with_watermark.png");
BufferedImage img = ImageIO.read(inputImage);
int width = img.getWidth();
int height = img.getHeight();
int fontSize = (width + height) / 80;
Graphics2D g = img.createGraphics();
g.setFont(new Font("黑体", Font.PLAIN, fontSize));
g.setColor(new Color(0, 0, 0, 30));
g.rotate(0.2);
// 间隔
int split = fontSize * 2;
// 文字占用的宽度
int xWidth = getStrWidth(str, fontSize);
// x,y可以绘制的数量,多加一个补充空白
int xCanNum = width / xWidth + 1;
int yCanNum = height / fontSize + 1;
for (int i = 1; i <= yCanNum; i++) {
int y = fontSize * i + split * i;
for (int j = 0; j < xCanNum; j++) {
int x = xWidth * j + split * j;
g.drawString(str, x, y - (fontSize + split) * j);
}
}
g.dispose();
ImageIO.write(img, "png", outputImage);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取字符串占用的宽度
*
* @param str 字符串
* @param fontSize 文字大小
* @return 字符串占用的宽度
*/
public static int getStrWidth(String str, int fontSize) {
char[] chars = str.toCharArray();
int fontSize2 = fontSize / 2;
int width = 0;
for (char c : chars) {
int len = String.valueOf(c).getBytes().length;
// 汉字为3,其余1
// 可能还有一些特殊字符占用2 等等,统统计为汉字·
if (len != 1) {
width += fontSize;
} else {
width += fontSize2;
}
}
return width;
}
}