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

这第一步当然是在网上下载一款字体啦,然后把下载的字体放在对应的文件位置,接下来就是代码了

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");
        Font dynamicFont = Font.createFont(Font.TRUETYPE_FONT, file);
//      方法2引用外部字体有可能会失败不起作用,建议使用方法3
//        Font font = new Font("微软雅黑", Font.PLAIN, 35); //水印字体 方法1
//        Font font = new Font(dynamicFont.getName(), Font.PLAIN, 35); //水印字体 方法2
        Font font = dynamicFont.deriveFont(Font.PLAIN, 35); //水印字体 方法3
        String srcImgPath = "E://15.jpg"; //源图片地址
        String tarImgPath = "E://" + System.currentTimeMillis() + ".jpg"; //待存储的地址
        String waterMarkContent = "时光蹉跎,看淡岁月你我";  //水印内容
        Color color = new Color(225, 225, 60); //水印图片色彩以及透明度
        addWaterMark(srcImgPath, tarImgPath, color, waterMarkContent, 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);
    }

}

经过本人亲测,妥妥的,附上一个获取计算文字占的像素长度方法

//计算文字占的像素长度
int sw = getSw(dynamicFont, content, fontSize);

private int getSw(Font dynamicFont, String content, int fontSize) {
        FontMetrics fm = FontDesignMetrics.getMetrics(dynamicFont.deriveFont(Font.PLAIN, fontSize));
        return fm.stringWidth(content);
    }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Spring Boot和Java实现PDF水印的示例代码: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.core.io.ClassPathResource; import org.springframework.util.ResourceUtils; import com.itextpdf.text.Document; import com.itextpdf.text.Element; import com.itextpdf.text.Font; import com.itextpdf.text.Image; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfStamper; @SpringBootApplication public class PdfWatermarkApplication { public static void main(String[] args) { SpringApplication.run(PdfWatermarkApplication.class, args); } public static void addWatermark(String inputFilePath, String outputFilePath, String watermarkText) { try { PdfReader reader = new PdfReader(inputFilePath); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFilePath)); BaseFont baseFont = BaseFont.createFont(ResourceUtils.getFile("classpath:font/arial.ttf").getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); Font font = new Font(baseFont, 50, Font.BOLD); int totalPages = reader.getNumberOfPages(); for (int i = 1; i <= totalPages; i++) { PdfContentByte content = stamper.getUnderContent(i); content.beginText(); content.setFontAndSize(baseFont, 50); content.setColorFill(BaseColor.LIGHT_GRAY); content.showTextAligned(Element.ALIGN_CENTER, watermarkText, PageSize.A4.getWidth() / 2, PageSize.A4.getHeight() / 2, 45); content.endText(); } stamper.close(); reader.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 你可以调用`addWatermark`方法来给PDF文件添水印。需要传入输入文件路径、输出文件路径和水印文本作为参数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值