給圖片加水印的主要步驟包括:
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");
}
效果圖