在图片上添加水印

发布时间 2023-06-15 15:01:50作者: smars1990

直接上代码:

 1 import cn.hutool.core.img.Img;
 2 import cn.hutool.core.img.ImgUtil;
 3 import cn.hutool.core.io.FileUtil;
 4 
 5 import java.awt.*;
 6 import java.awt.image.BufferedImage;
 7 import java.io.File;
 8 import java.util.Date;
 9 
10 public class WatermarkUtils {
11     /*水印字字体大小*/
12     public static Integer FONT_SIZE = 20;
13     /*水印字字体*/
14     public static String FONT_NAME = "黑体";
15     /*水印字体透明度*/
16     public static Float ALPHA = 0.8f;
17     /**
18      * @param sourceFile 源图片
19      * @param destFile   目标图片
20      **/
21     public static void init (File sourceFile,  File destFile ) {
22 
23         //添加水印至左上角
24         Img img = Img.from(ImgUtil.read(sourceFile)).setPositionBaseCentre(false);
25 
26         BufferedImage sourceImage  = ImgUtil.read(sourceFile);
27         int imgWidth = -sourceImage.getWidth(null)/2 +115;
28         int imgHeight = -sourceImage.getHeight(null)/2 +10;
29 
30         Image imageFile = img.pressText(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN), Color.BLUE, new Font(FONT_NAME, Font.BOLD, FONT_SIZE), imgWidth, imgHeight, ALPHA).getImg();
31 
32         ImgUtil.write(imageFile, destFile);
33     }
34 
35     public static void main(String[] args) throws Exception {
36         // 添加水印
37 //        String srcImgPath = "C:\\Users\\Administrator\\Desktop\\test.png"; //源图片地址
38 //        String tarImgPath = "G:\\picture\\dd.png"; //待存储的地址
39 
40         String srcImgPath = "G:\\picture\\3.jpg"; //源图片地址
41         String tarImgPath = "G:\\picture\\3.jpg"; //待存储的地址
42 
43 
44         WatermarkUtils.init(FileUtil.file(srcImgPath),FileUtil.file(tarImgPath) );
45     }
46 
47 }

 

总结:

遇到在linux 服务上添加 日期 水印乱码; 解决方案是:Linux中没有对应的字体;可以参考 : https://blog.csdn.net/weixin_42168046/article/details/122731756

 走在踩坑路上的人,还不知道 还能走多远..