有需求将前端传过来的图片base64添加水印并保存到文件服务器中,所以写一个公共方法,该方法实现了水印文字居中,并且倾斜。DvMrmsConstants.PDF.WatermarkWords是水印文字常量,DvMrmsConstants.PDF.WatermarkAngle是水印倾斜角度(逆时针)
public static byte[] addImageWaterMark(String imageBase64) throws Exception {
String[] base64Parts = imageBase64.split(",");
byte[] imageBytes = Base64.getDecoder().decode(base64Parts[1]);
InputStream inputStream = null;
try {
// 构造 BufferedImage 对象
inputStream = new ByteArrayInputStream(imageBytes);
BufferedImage bufferedImage = ImageIO.read(inputStream);
// 添加水印
Graphics2D graphics = bufferedImage.createGraphics();
Font font = new Font("Arial", Font.BOLD, DvMrmsConstants.PDF.WatermarkFontSize);
FontMetrics fm = graphics.getFontMetrics(font);
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setFont(font);
Color color = new Color(255, 255, 255, 128);
graphics.setColor(color);
String watermark = DvMrmsConstants.PDF.WatermarkWords;
int x = (bufferedImage.getWidth() - fm.stringWidth(watermark)) / 2;
int y = bufferedImage.getHeight() / 2;
AffineTransform affineTransform = new AffineTransform();
affineTransform.rotate(Math.toRadians(360 - DvMrmsConstants.PDF.WatermarkAngle), bufferedImage.getWidth() / 2d, bufferedImage.getHeight() / 2d);
graphics.setTransform(affineTransform);
graphics.drawString(watermark, x, y);
// 将 BufferedImage 转换为 byte 数组
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "jpg", baos);
byte[] watermarkedImageBytes = baos.toByteArray();
return watermarkedImageBytes;
} catch (Exception e) {
e.printStackTrace();
} finally {
inputStream.close();
}
return null;
}