//添加水印
public static void addWaterMark(HttpServletRequest request, WritableSheet sheet) throws Exception{
User user = UserInfoUtil.getLoginUser(request);
String userId = (String) user.getExtValue("namecode");
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String sysdate = sdf.format(date);
if (userId != null && !"".equals(userId)
&& userId.length() < 20) {
try {
File file = createWaterMark(userId+" "+sysdate);
byte[] imageByte = new byte[(int) file.length()];
fis = new FileInputStream(file);
fis.read(imageByte);
sheet.setWaterMarkImage(imageByte, width, height);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 生成水印图片
*
* @param watermark
* @return
* @throws IOException
*/
public static File createWaterMark(String watermark) throws IOException {
// 获取bufferedImage对象
BufferedImage bi = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 处理背景色,设置为 白色
int minx = bi.getMinX();
int miny = bi.getMinY();
for (int i = minx; i < width; i++) {
for (int j = miny; j < height; j++) {
bi.setRGB(i, j, 0xffffff);
}
}
Font font = new Font("华文细黑", Font.ITALIC, 20);
// 获取Graphics2d对象
Graphics2D g2d = bi.createGraphics();
// 设置字体颜色为灰色
g2d.setColor(Color.LIGHT_GRAY);
// 设置图片的属性
g2d.setStroke(new BasicStroke(1));
// 设置字体
g2d.setFont(new Font("华文细黑", Font.ITALIC, 20));
// 设置字体倾斜度
g2d.rotate(Math.toRadians(-10), (double) bi.getWidth() / 2, (double) bi.getHeight() / 2);
// 写入水印文字 原定高度过小,所以累计写水印,增加高度
for (int i = 1; i < 4; i++) {
g2d.drawString(watermark, 100, 300 * i);
}
// 设置透明度
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
// 释放对象
g2d.dispose();
ByteArrayOutputStream os = new ByteArrayOutputStream();
String targetImagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath()+"WaterMark";
ImageIO.write(bi, "png", new File(targetImagePath));
watermarkFileName = new File(targetImagePath);
// 通过bmp写入文件
BMPEncoder.write(bi, watermarkFileName);
return watermarkFileName;
}
评论0