public static boolean addImageWatermarking(String filePath, String fileAddress, String watermarkingName) {
try {
File newFile = new File(filePath);
Image image = ImageIO.read(newFile);
int width = image.getWidth(null);
int height = image.getHeight(null);
int size = width / 300 * 10;
if (size == 0) {
size = 10;
}
Font font = new Font("宋体", Font.BOLD, size);
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = bufferedImage.createGraphics();
graphics.drawImage(image, 0, 0, width, height, null);
graphics.setColor(Color.lightGray);
graphics.setFont(font);
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f));
graphics.rotate(Math.toRadians(-45), width, height);
JLabel label = new JLabel(watermarkingName);
FontMetrics metrics = label.getFontMetrics(font);
int waterWidth = metrics.stringWidth(label.getText());
int rowsNumber = (height / waterWidth) + (height % waterWidth);
int columnsNumber = width / waterWidth;
if (rowsNumber < 1) {
rowsNumber = 1;
}
if (columnsNumber < 1) {
columnsNumber = 1;
}
for (int j = 0; j < rowsNumber; j++) {
for (int i = 0; i < columnsNumber; i++) {
graphics.drawString(watermarkingName, i * waterWidth + j * waterWidth, -i * waterWidth + j * waterWidth);
}
}
graphics.dispose();
FileOutputStream outputStream = new FileOutputStream(fileAddress);
ImageIO.write(bufferedImage, "jpg", outputStream);
outputStream.flush();
outputStream.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
|