import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import javax.imageio.ImageIO;
public class WatermarkUtils {
private static float alpha = 0.6f;
public static final int FONT_SIZE = 38;
private static Font font = new Font("宋体", Font.BOLD, FONT_SIZE);
private static Color color = Color.lightGray;
private static final int XMOVE = 150;
private static final int YMOVE = 150;
public static void ImageByText(String srcImgPath, String targerPath, String logoText) {
ImageByText(logoText, srcImgPath, targerPath, -25);
}
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 ImageByText(String logoText, String srcImgPath, String targerPath, Integer degree) {
InputStream is = null;
OutputStream os = null;
try {
Image srcImg = ImageIO.read(new File(srcImgPath));
int width = srcImg.getWidth(null);
int height = srcImg.getHeight(null);
BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null),
BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH),
0, 0, null);
if (null != degree) {
g.rotate(Math.toRadians(degree), (double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2);
}
g.setColor(color);
g.setFont(font);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
int x = -width / 2;
int y = -height / 2;
int markWidth = FONT_SIZE * getTextLength(logoText);
int markHeight = FONT_SIZE;
while (x < width * 1.5) {
y = -height / 2;
while (y < height * 1.5) {
g.drawString(logoText, x, y);
y += markHeight + YMOVE;
}
x += markWidth + XMOVE;
}
g.dispose();
os = new FileOutputStream(targerPath);
ImageIO.write(buffImg, "JPG", os);
System.out.println("添加水印文字成功!");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != is)
is.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
if (null != os)
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
String srcImgPath = "C:\Users\Administrator\Desktop\1665208963512.jpg";
String logoText = "2022-08-25 孔繁浩";
String targerTextPath2 = "C:\Users\Administrator\Desktop\a.jpg";
System.out.println("给图片添加水印文字开始...");
WatermarkUtils.ImageByText(logoText, srcImgPath, targerTextPath2, -25);
System.out.println("给图片添加水印文字结束...");
}
}