在数字时代,保护原创内容的重要性不言而喻。而添加水印是一种常见的保护手段,既可以标识版权,又可以防止他人非法使用。本文将详细介绍如何在Java中批量添加水印,支持图片、文档等多种格式,帮助你轻松实现原创内容的保护。
一、图片水印添加
1.1 使用Java库
在Java中,我们可以使用第三方库来实现图片水印的添加。以下是一些常用的库:
- Apache Commons Imaging:这是一个强大的图像处理库,支持多种图像格式。
- ImageMagick:这是一个功能强大的图像处理工具,Java可以通过JAI(Java Advanced Imaging)集成使用。
1.2 添加水印示例
以下是一个使用Apache Commons Imaging库添加图片水印的示例代码:
import org.apache.commons.imaging.Imaging;
import org.apache.commons.imaging.ImageFormats;
import org.apache.commons.imaging.common.ImageMetadata;
import org.apache.commons.imaging.common.ImageMetadataItem;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
public class ImageWatermark {
public static void addWatermark(String inputPath, String outputPath, String watermarkText) throws Exception {
BufferedImage image = Imaging.getBufferedImage(new File(inputPath));
Graphics2D g2d = (Graphics2D) image.getGraphics();
AlphaComposite alphaChannel = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f);
g2d.setComposite(alphaChannel);
g2d.setColor(Color.BLUE);
g2d.setFont(new Font("Arial", Font.BOLD, 64));
FontMetrics fontMetrics = g2d.getFontMetrics();
Rectangle2D rect = fontMetrics.getStringBounds(watermarkText, g2d);
int centerX = (image.getWidth() - (int) rect.getWidth()) / 2;
int centerY = image.getHeight() / 2;
g2d.drawString(watermarkText, centerX, centerY);
g2d.dispose();
Imaging.writeImage(image, new File(outputPath), ImageFormats.JPEG, null);
}
public static void main(String[] args) {
try {
addWatermark("input.jpg", "output.jpg", "Copyright © 2022");
} catch (Exception e) {
e.printStackTrace();
}
}
}
二、文档水印添加
2.1 使用Java库
在Java中,我们可以使用以下库来实现文档水印的添加:
- Apache POI:这是一个处理Microsoft Office文档的库,支持Word、Excel、PowerPoint等格式。
- iText:这是一个功能强大的PDF处理库,支持添加水印、加密、签名等功能。
2.2 添加水印示例
以下是一个使用Apache POI库添加Word文档水印的示例代码:
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class DocumentWatermark {
public static void addWatermark(String inputPath, String outputPath, String watermarkText) throws IOException {
XWPFDocument doc = new XWPFDocument(new FileInputStream(inputPath));
for (XWPFParagraph paragraph : doc.getParagraphs()) {
for (XWPFRun run : paragraph.getRuns()) {
run.setText(watermarkText + run.getText());
}
}
FileOutputStream out = new FileOutputStream(outputPath);
doc.write(out);
out.close();
}
public static void main(String[] args) {
try {
addWatermark("input.docx", "output.docx", "Confidential");
} catch (IOException e) {
e.printStackTrace();
}
}
}
三、总结
本文详细介绍了如何在Java中批量添加水印,支持图片、文档等多种格式。通过使用Apache Commons Imaging、Apache POI等库,我们可以轻松实现原创内容的保护。希望本文对你有所帮助!
