Java图片加水印
采用Java自带的Image IO
废话不多说,上菜
1. 文字水印
1 import sun.font.FontDesignMetrics;
2
3 import javax.imageio.ImageIO;
4 import java.awt.*;
5 import java.awt.image.BufferedImage;
6 import java.io.File;
7 import java.io.FileOutputStream;
8 import java.io.IOException;
9
10 /**
11 * @Author ChengJianSheng
12 * @Date 2021/6/10
13 */
14 public class WatermarkUtil {
15
16 public static void main(String[] args) throws IOException {
17 addText("F:/1.jpeg", "我的梦想是成为火影");
18 }
19
20 /**
21 * 加文字水印
22 * @param srcPath 原文件路径
23 * @param content 文字内容
24 * @throws IOException
25 */
26 public static void addText(String srcPath, String content) throws IOException {
27 // 读取原图片信息
28 BufferedImage srcImage = ImageIO.read(new File(srcPath));
29 int width = srcImage.getWidth();
30 int height = srcImage.getHeight();
31
32 // 创建画笔,设置绘图区域
33 BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
34 Graphics2D g = bufferedImage.createGraphics();
35 g.drawImage(srcImage, 0, 0, width, height, null);
36 // g.drawImage(srcImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
37
38 g.setFont(new Font("宋体", Font.PLAIN, 32));
39 g.setColor(Color.RED);
40
41 // 计算文字长度
42 int len = g.getFontMetrics(g.getFont()).charsWidth(content.toCharArray(), 0, content.length());
43 FontDesignMetrics metrics = FontDesignMetrics.getMetrics(g.getFont());
44 int len2 = metrics.stringWidth(content);
45 System.out.println(len);
46 System.out.println(len2);
47
48 // 计算文字坐标
49 int x = width - len - 10;
50 int y = height - 20;
51 // int x = width - 2 * len;
52 // int y = height - 1 * len;
53
54 g.drawString(content, x, y);
55
56 g.dispose();
57
58 // 输出文件
59 FileOutputStream fos = new FileOutputStream("F:/2.png");
60 ImageIO.write(bufferedImage, "png", fos);
61 fos.flush();
62 fos.close();
63 }
64
65 }


