spring boot 使用外部字体给图片加水印

1,523 阅读2分钟
这第一步当然是在网上下载一款字体啦,然后把下载的字体放在对应的文件位置,接下来就是代码了
package com.example.demo;
 
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
 
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
 
@RestController
public class LoadFontController {
 
 
    @GetMapping("/test")
    public void test() throws IOException, FontFormatException {
        File file = new File("E://包图小白体.ttf");
        FileInputStream fs = new FileInputStream(file);
        Font dynamicFont = Font.createFont(Font.TRUETYPE_FONT, fs);
        fs.close();
        //Font font = new Font("微软雅黑", Font.PLAIN, 35); //水印字体
        Font font = new Font(dynamicFont.getName(), Font.PLAIN, 35); //水印字体
        String srcImgPath = "E://15.jpg"; //源图片地址
        String tarImgPath = "E://" + System.currentTimeMillis() + ".jpg"; //待存储的地址
        String waterMarkContent = "时光蹉跎,看淡岁月你我";  //水印内容
        Color color = new Color(225, 225, 60); //水印图片色彩以及透明度
        addWaterMark(srcImgPath, tarImgPath, waterMarkContent, color, font);
    }
 
    public void addWaterMark(String srcImgPath, String tarImgPath, Color markContentColor, String content, Font font) throws IOException {
        // 读取原图片信息
        File srcImgFile = new File(srcImgPath);//得到文件
        Image srcImg = ImageIO.read(srcImgFile);//文件转化为图片
        int srcImgWidth = srcImg.getWidth(null);//获取图片的宽
        int srcImgHeight = srcImg.getHeight(null);//获取图片的高
        // 加水印
        BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bufImg.createGraphics();
        g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
        g.setColor(markContentColor); //根据图片的背景设置水印颜色
        g.setFont(font);  //设置字体
        //设置水印的坐标 如果水印长度超过图片宽度则换行
        int fontLen = getWatermarkLength(content, g); // 水印文字总长度
        int line = fontLen / srcImgWidth;//文字长度相对于图片宽度应该有多少行
        int y = (line + 1) * font.getSize();
        System.out.println("水印文字总长度:" + fontLen + ",图片宽度:" + srcImgWidth + ",字符个数:" + content.length());
        //文字叠加,自动换行叠加
        int tempX = 50; // 文字初始x坐标位置
        int tempY = y;  // 文字初始y坐标位置
        int tempCharLen;//单字符长度
        int tempLineLen = 0;//单行字符总长度临时计算
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < content.length(); i++) {
            char tempChar = content.charAt(i);
            tempCharLen = getCharLen(tempChar, g);
            tempLineLen += tempCharLen;
            if (tempLineLen >= srcImgWidth - 70) {
                //长度已经满一行,进行文字叠加
                g.drawString(sb.toString(), tempX, tempY);
                sb.delete(0, sb.length());//清空内容,重新追加
                tempY += font.getSize();
                tempLineLen = 0;
            }
            sb.append(tempChar);//追加字符
        }
        g.drawString(sb.toString(), tempX, tempY);//最后叠加余下的文字
        g.dispose();
        // 输出图片
        FileOutputStream outImgStream = new FileOutputStream(tarImgPath);
        ImageIO.write(bufImg, "jpg", outImgStream);
        System.out.println("添加水印完成");
        outImgStream.flush();
        outImgStream.close();
    }
 
 
    /**
     * 获取水印文字总长度
     *
     * @param waterMarkContent
     * @param g
     * @return
     */
    public int getWatermarkLength(String waterMarkContent, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
    }
 
 
    /**
     * 获取水印对应文字的位置
     *
     * @param c
     * @param g
     * @return
     */
    public int getCharLen(char c, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charWidth(c);
    }
}

经过本人亲测,妥妥的