下面是加水印的函数,直接在上传图片的地方调用就好了,两个参数分别是File和String。
/**
* 加水印
* @param ifile
*/
public void addWaterMark(File ifile,String url){
try {
String waterMarkContent="论坛报名专用";
Image srcImg = ImageIO.read(ifile);
int srcImgWidth = srcImg.getWidth(null);
int srcImgHeight = srcImg.getHeight(null);
// 加水印
BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufImg.createGraphics();
g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
g.setColor(new Color(255,0,0)); //根据图片的背景设置水印颜色
g.setFont(new Font("宋体",Font.PLAIN,50)); //设置字体
//设置水印的坐标
int x = 50;//srcImgWidth - 2*getWatermarkLength(waterMarkContent, g);
int y = 100;//srcImgHeight - 2*getWatermarkLength(waterMarkContent, g);
g.drawString(waterMarkContent, x, y); //画出水印
g.dispose();
// 输出图片
FileOutputStream outImgStream = new FileOutputStream(url);
ImageIO.write(bufImg, "jpg", outImgStream);
System.out.println("添加水印完成");
outImgStream.flush();
outImgStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private int getWatermarkLength(String waterMarkContent, Graphics2D g) {
return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
}