撰写时间:2019年2月1日
(说明:图片添加水印来自其他作者,并非本人原创)
原创作者:http://www.cnblogs.com/personnel/p/4582904.html
一、功能实现
// 这个路径相对应当前应用的目录
/*String uploadPath = req.getServletContext().getRealPath("/upload");*/
String uploadPath = "D:/112017Nian/项目/upload";
// 如果目录不存在则创建
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();}
//添加水印▽
File file = new File(uploadPath + "/" + fileName);
if (!file.exists()) {
System.out.println("找不到文件");
return;
}
ImageIcon icon = new ImageIcon(file.getPath());
BufferedImage bufferedImage = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = (Graphics2D) bufferedImage.getGraphics();
// 图像呈现
g2d.drawImage(icon.getImage(), 0, 0, null);
// AlphaComposite 类实现一些基本的 alpha 合成规则,将源色与目标色组合,
// 在图形和图像中实现混合和透明效果
AlphaComposite alpha = AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, 0.7f);
g2d.setComposite(alpha);
// 水印颜色
g2d.setColor(Color.white);
// 为呈现算法设置首选项(此处为文本抗锯齿提示键)的值
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
// 水印字体
//g2d.setFont(new Font("Arial", Font.ITALIC, 16));
g2d.setFont(new Font("楷体_GB2312", Font.PLAIN, 18));
// 水印文字
String watermark = "@藤叶子";
// 文本呈现
g2d.drawString(watermark, (icon.getIconWidth() - 80),
(icon.getIconHeight() - 15));
g2d.dispose();
String filesSCTPM = SHIJIAN + "__AA__"+ files;
File fileout = new File(uploadPath + "/" + filesSCTPM );
// 生成图片
ImageIO.write(bufferedImage, "jpg", fileout);
//添加水印△
效果图:会保存两张图片,一张是原图,一张是添加了水印的图片
二、功能实现
效果图: