//由于项目的需要,为Webwork的FileUploadInterceptor编写了一个用来为上传的图片添加水印的拦截器,水印的文本内容、字体、样式通过配置文件设定。以下是添加水印部分的代码:
//读取文件,获得BufferedImage对象
BufferedImage image=ImageIO.read(file);
//获得Graphics2d绘图缓冲区
Graphics2D g2d=(Graphics2D)image.getGraphics();
//设定图形叠加时的透明效果
AlphaComposite ac=AlphaComposite.getInstance(AlphaComposite.SRC_OVER,.7f);
g2d.setComposite(ac);
//设定抗锯齿渲染
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
//获得图像的宽度和高度,并根据图像的宽度和高度设定字号及位置
int width=image.getWidth();
int height=image.getHeight();
int fontSize=width/8;
int x=2;
int y=height-6;
//获得字体样式
int fontStyle=0;
if(style.equals("plain"))
fontStyle=Font.PLAIN;
else if(style.equals("bold"))
fontStyle=Font.BOLD;
else if(style.equals("italic"))
fontStyle=Font.ITALIC;
//设定字体
Font watermarkFont=new Font(font,fontStyle,fontSize);
g2d.setFont(watermarkFont);
//打印水印
g2d.setColor(Color.WHITE);
g2d.drawString(content,x,y);
//获得文件的扩展名
String exp=getExp(file.getName());
//输出带有水印的图片,覆盖原来的图片
ImageIO.write(image,exp,file);