Java添加文字水印

    // 水印颜色
    private String fontColor = "#FFFFFF";
    // 文字大小
    private Integer fontSize = 40;
    private volatile Integer tmpTextHeight;

    /**
     * 为文件打水印
     */
    private BufferedImage watermark(File file, List<String> textList) throws IOException {
        BufferedImage image = ImageIO.read(file);
        Font font = new Font("黑体", Font.PLAIN, fontSize);
        // Font font = new Font("黑体", Font.BOLD, 20);

        if (tmpTextHeight == null) {
            synchronized (this) {
                if (tmpTextHeight == null) {
                    // 临时对象
                    Graphics2D tmpG2d = image.createGraphics();
                    tmpG2d.setFont(font);
                    // 获取每行文本的高度
                    tmpTextHeight = tmpG2d.getFontMetrics().getHeight();
                    tmpG2d.dispose();
                }
            }
        }

        BufferedImage combined = new BufferedImage(image.getWidth(), image.getHeight() + tmpTextHeight * (textList.size() + 1), BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = combined.createGraphics();
        // 设置底色为黑色
        //g2d.setColor(Color.BLACK);
        //g2d.fillRect(0, 0, combined.getWidth(), combined.getHeight());

        // 画原图
        g2d.drawImage(image, 0, 0, null);
        g2d.setFont(font);
        g2d.setColor(Color.decode(fontColor));

        // 画水印文字
        for (int i = 0; i < textList.size(); i++) {
            g2d.drawString(textList.get(i), 0, image.getHeight() + tmpTextHeight * (i + 1));
        }

        g2d.dispose();
        // ImageIO.write(combined, "JPEG", file);

        return combined;
    }
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值