java加水印
给图片加水印的主要步骤包括:
1、获取原图的画笔
2、设置水印信息、水印位置
3、在原图上画出水印
工具代码
/**
* 在图片右下角添加白色文字水印
* @param is
* @param os
* @param text
* @throws IOException
*/
public static void makeWatermark(InputStream is, OutputStream os, String text, String format) throws IOException {
BufferedImage image = ImageIO.read(is);
if (image != null) {
int width = image.getWidth();
int height = image.getHeight();
//计算字体大小
int fontSize = (int)(width * height * 0.000008 + 13);
Font font = new Font("宋体", Font.PLAIN, fontSize);
Graphics2D g = image.createGraphics();
g.setFont(font);
g.setColor(Color.white); //水印颜色-白色
// // 透明度
// float alpha = 0.9f;
// g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
int x = width - getWatermarkLength(text, g) - 10;
x = x < 0 ? 0 : x;
int y = height - 10;
y = y < 0 ? 0 : y;
//对线段的锯齿状边缘处理
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawString(text, x, y);
g.dispose();
ImageIO.write(image, format, os);
}
}
/**
* 获取水印文字总长度
* @param text 水印的文字
* @param g
* @return 水印文字总长度
*/
private static int getWatermarkLength(String text, Graphics g) {
return g.getFontMetrics(g.getFont()).charsWidth(
text.toCharArray(), 0, text.length());
}
测试代码
/**
* 测试制作水印
* @throws IOException
* @throws FileNotFoundException
*/
@Test
public void testMakeWatermark() throws FileNotFoundException, IOException {
String imageName = "java_coffee.jpg";
String srcPath = IMAGE_PATH + imageName;
imageName = "java_coffee_wm.jpg";
String detsPath = IMAGE_PATH + imageName;
ImageUtil.makeWatermark(new FileInputStream(srcPath),
new FileOutputStream(detsPath), "测试水印", "jpg");
}
效果图