// 水印颜色
private String fontColor = "#FFFFFF";
// 文字大小
private Integer fontSize = 40;
private volatile Integer tmpTextHeight;
/**
* 为文件打水印
*/
private BufferedImage watermark(File file, List<String> textList) throws IOException {
BufferedImage image = ImageIO.read(file);
Font font = new Font("黑体", Font.PLAIN, fontSize);
// Font font = new Font("黑体", Font.BOLD, 20);
if (tmpTextHeight == null) {
synchronized (this) {
if (tmpTextHeight == null) {
// 临时对象
Graphics2D tmpG2d = image.createGraphics();
tmpG2d.setFont(font);
// 获取每行文本的高度
tmpTextHeight = tmpG2d.getFontMetrics().getHeight();
tmpG2d.dispose();
}
}
}
BufferedImage combined = new BufferedImage(image.getWidth(), image.getHeight() + tmpTextHeight * (textList.size() + 1), BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = combined.createGraphics();
// 设置底色为黑色
//g2d.setColor(Color.BLACK);
//g2d.fillRect(0, 0, combined.getWidth(), combined.getHeight());
// 画原图
g2d.drawImage(image, 0, 0, null);
g2d.setFont(font);
g2d.setColor(Color.decode(fontColor));
// 画水印文字
for (int i = 0; i < textList.size(); i++) {
g2d.drawString(textList.get(i), 0, image.getHeight() + tmpTextHeight * (i + 1));
}
g2d.dispose();
// ImageIO.write(combined, "JPEG", file);
return combined;
}
Java添加文字水印
最新推荐文章于 2024-09-08 11:09:43 发布