用途:对扫描文件在查看是加水印。
获取用户名并生成水印方法。
/**
* 获取当前用户;用户名生成水印
*
* @return
*/
public String getName() throws Exception {
String userName = SessionUtil.getCurrentUser().getUsername();
String userId = SessionUtil.getCurrentUser().getId();
String userLogin = null;
List<PfUserVo> list = userService.getAllUsers();
for (PfUserVo user : list) {
if (user.getUserId().equals(userId))
if (user.getUserNo() != null) {
userLogin = user.getLoginName();
}
}
HttpServletRequest request = ServletActionContext.getRequest();
String basePath = request.getSession().getServletContext().getRealPath("/");
//图片存放文件是否存在
File file = new File(basePath + File.separator + "waterMarked");
if (!file.exists()) {
file.mkdirs();
}
String filename = userLogin + ".png";
File tmp = new File(file.getPath() + File.separator + filename);
//水印图片是否存在
if (!tmp.exists()) {
createImage(userName, new Font("宋体", Font.BOLD, 32), tmp, 200, 200);
}
return renderJson(userLogin);
}
// 根据str,font的样式以及输出文件目录
public static void createImage(String str, Font font, File outFile,
Integer width, Integer height) throws Exception {
// 创建图片
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
g.setClip(0, 0, width, height);
g.setColor(Color.white);// 先用白色填充整张图片,也就是背景
g.fillRect(0, 0, width, height);
g.setColor(Color.gray);// 在换成灰色
g.setFont(font);// 设置画笔字体
//设置透明度
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,0.8F));
//设置旋转角度及旋转中心
//Math.toDegrees():将用弧度表示的角转换为近似相等的用角度表示的角
//Math.toRadians():将用角度表示的角转换为近似相等的用弧度表示的角,rotate的第一个参数是用弧度表示的,所以使用toRadians方法
//相同的设置成30,结果为:toDegrees方法添加倒置的水印,toRadians添加正置的水印
g.rotate(Math.toRadians(-30),image.getWidth()/2, image.getHeight()/2);
/** 设置文字居中 */
FontMetrics fm = g.getFontMetrics(font);
int stringWidth = fm.stringWidth(str);
int stringAscent = fm.getAscent();
int xCoordinate = width/2 - stringWidth/2;
int yCoordinate = height/2 +stringAscent/2;
g.drawString(str, xCoordinate, yCoordinate);// 画出字符串
g.dispose();
ImageIO.write(image, "png", outFile);// 输出png图片
}
水印作为背景图片覆盖于扫描文件。
/**
* 水印
* @param
*/
function getWaterMarked(){
$("#image").each(function(){
Ext.Ajax.request({
url: 'demo!getName.action',
success: function (r) {
debugger
var waterMarked = Ext.decode(r.responseText);
var div = document.getElementById("imgPanel");
var width = div.offsetWidth*0.98;
var heigth = div.offsetHeight*0.98;
styleString = "left:0px;width:"+ width +"px;height:"+ heigth +"px;";
styleString = styleString + "display:inline-block;position:absolute;top:0;left:0;filter:alpha(opacity=20);opacity:0.2;";
styleString = styleString + "background-image:url(../demo/tmp/waterMarked/" + waterMarked +".png)";
//追加水印div
$("#imgPanel").after('<div id="shuiYinDiv" style='+styleString+'>');
}
});
});
}