java之批量给某目录下指定的图片格式添加水印文字效果
public static void main(String[] args) throws Exception {
allwaterimg(new File("F:/download/壁纸"), new File("F:/beg"));
}
public static void allwaterimg(File src, File dst) throws Exception {
if (src.isFile() && src.getName().endsWith(".jpg")) {
waterimg(src, dst);
}
else if (src.isDirectory()) {
for (File ff : src.listFiles()) {
if (!dst.exists()) {
dst.mkdirs();
}
if (ff.isDirectory()) {
allwaterimg(ff, new File(dst + "/" + ff.getName()));
}
else if (ff.isFile() && ff.getName().endsWith(".jpg")) {
waterimg(ff, new File(dst, ff.getName()));
}
}
}
}
public static void waterimg(File src, File dst) throws Exception {
BufferedImage img = ImageIO.read(src);
int iw = img.getWidth();
int ig = img.getHeight();
Graphics2D g = img.createGraphics();
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
String txt = "版权所有 禁止复制";
txt = String.format("%tF %<tT", System.currentTimeMillis());
var font = Font.createFont(Font.TRUETYPE_FONT, new File("fonts/FZZYJW.TTF")).deriveFont(Font.BOLD, 100f);
g.setFont(font);
Random rand = new Random();
Color color = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
g.setColor(color);
FontMetrics fm = g.getFontMetrics(font);
int ascent = fm.getAscent();
int fw = fm.stringWidth(txt);
int tx = 0 + 10;
int ty = ascent + 10;
tx = rand.nextInt(10, iw - fw - 10);
ty = rand.nextInt(ascent + 10, ig - 5 - 10);
g.drawString(txt, tx, ty);
g.dispose();
ImageIO.write(img, "jpg", new File(dst.getParent(),UUID.randomUUID()+".jpg"));
}