工作中遇到给图片添加文字水印的需求,记录下来方便之后查阅
需求内容:
给一张图片添加指定文字水印,使一张图片上有多个水印内容,并且设定一个水印开关,可指定是否添加水印。
public static byte[] watermarkAdd(byte[] image, String waterMarkText, String fontName, int fontStyle, Color color, Integer degree,
float alpha, String isOpen) {
if (null == image)
return null;
if ("off".equalsIgnoreCase(isOpen))
return image;
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
// 得到源图片
Image srcImg = ImageIO.read(new ByteArrayInputStream(image));
int imgWidth = srcImg.getWidth(null);
int imgHeight = srcImg.getHeight(null);
BufferedImage buffImg = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
// 得到画笔对象
Graphics2D g = buffImg.createGraphics();
// 设置对线段的锯齿状边缘处理
// g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(srcImg.getScaledInstance(imgWidth, imgHeight, Image.SCALE_SMOOTH), 0, 0, null);
// 设置水印文字大小
int fontSize = buffImg.getWidth(null) / 300 * 8;
// 设置水印Font
g.setFont(new Font(fontName,fontStyle,fontSize));
// 设置水印文字颜色
g.setColor(color);
// 设置水印旋转
if (null != degree) {
g.rotate(Math.toRadians(degree), (double) imgWidth / 2, (double) imgHeight / 2);
}
// 设置水印文字透明度
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
// 计算水印文字的大小
int textWidth = fontSize * getLength(waterMarkText);
int textHeight = fontSize;
// 循环打印多个水印
for (int y = -imgHeight; y < imgHeight * 2; y += textHeight + fontSize * 3) {
for (int x = 0; x < imgWidth * 2; x += textWidth + fontSize * 3 / 2) {
// 笫一参数-> 设置的内容,后面两个参数->文字在图片上的坐标位置
g.drawString(waterMarkText, x, y);
}
}
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
// 释放资源
g.dispose();
// 生成图片
ImageIO.write(buffImg, "JPG", os);
return os.toByteArray();
} catch (IOException e) {
log.error("mark error", e);
}
return image;
}
public static int getLength(String text) {
int textLength = text.length();
int length = textLength;
for (int i = 0; i < textLength; i++) {
if (String.valueOf(text.charAt(i)).getBytes().length > 1) {
length++;
}
}
return (length % 2 == 0) ? length / 2 : length / 2 + 1;
}



