图片添加水印
public class AddMarkHelper {
public static void main ( String[ ] args) {
new AddMarkHelper ( ) . addWaterMark ( "天山雪莲" , "D://579b1f19410c0.jpg" , "D://11111.jpg" ) ;
}
public int getWatermarkLength ( String waterMarkContent, Graphics2D g) {
return g. getFontMetrics ( g. getFont ( ) ) . charsWidth ( waterMarkContent. toCharArray ( ) , 0 , waterMarkContent. length ( ) ) ;
}
public void addWaterMark ( String waterMarkContent, String picUrl, String tarImgPath) {
Color color = new Color ( 255 , 200 , 0 , 118 ) ;
Font font = new Font ( "宋体" , Font. CENTER_BASELINE, 45 ) ;
try {
File file = new File ( picUrl) ;
BufferedImage buImage = ImageIO. read ( file) ;
int width = buImage. getWidth ( ) ;
int height = buImage. getHeight ( ) ;
BufferedImage bufferedImage = new BufferedImage ( width, height, BufferedImage. TYPE_INT_BGR) ;
Graphics2D g = bufferedImage. createGraphics ( ) ;
g. drawImage ( buImage, 0 , 0 , width, height, null) ;
g. setColor ( color) ;
g. setFont ( font) ;
int x = width - 2 * getWatermarkLength ( waterMarkContent, g) ;
int y = height - 1 * getWatermarkLength ( waterMarkContent, g) ;
g. drawString ( waterMarkContent, x, y) ;
g. dispose ( ) ;
FileOutputStream outImgStream = new FileOutputStream ( tarImgPath) ;
ImageIO. write ( bufferedImage, "jpg" , outImgStream) ;
System. out. println ( "添加水印完成" ) ;
outImgStream. flush ( ) ;
outImgStream. close ( ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
}
}