Java给图片添加文字水印

1.编写工具类
package com.test;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * 水印处理工具
 * @author visy.wang
 * @date 2021/10/20 11:40
 */
public class WatermarkUtil {

    /**
     * 添加文字水印
     * @param srcFile 源文件
     * @param text 添加的文本内容
     * @param font 文本字体
     * @param color 文本颜色
     * @throws IOException
     */
    public static void addTextWatermark(File srcFile, String text, Font font, Color color) throws IOException {
        //文件转图片
        Image image = ImageIO.read(srcFile);

        //获取图片尺寸
        int width = image.getWidth(null), height = image.getHeight(null);

        //创建空的画布
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        //创建画笔
        Graphics2D g = bufferedImage.createGraphics();

        //把图片画在画布上, x和y是开始画的位置,这里是左上角(0,0)
        g.drawImage(image, 0, 0, width, height, null);

        //设置水印字体和颜色
        g.setFont(font);
        g.setColor(color);
        //设置透明度
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f));

        //计算水印位置-右下角:英文
        //int h = height-font.getSize(), w = width-text.length()*font.getSize()/2-10;
        //计算水印位置-右下角:中文
        int h = height-font.getSize(), w = width-text.length()*font.getSize()-10;

        //画水印
        g.drawString(text, w, h);

        //释放资源
        g.dispose();

        String fileFullName = srcFile.getName();
        int splitIndex = fileFullName.lastIndexOf(".");
        String fileName = fileFullName.substring(0, splitIndex);
        String extName = fileFullName.substring(splitIndex + 1);

        //写入本地磁盘, 使用时按具体情况处理
        ImageIO.write(bufferedImage, extName, new File("D:\\test\\"+fileName+"_watermark."+extName));

    }
}

2.测试
public static void main(String[] args) throws IOException{
    File file = new File("D:\\test\\src.jpg");
    WatermarkUtil.addTextWatermark(file, "我是水印", new Font("黑体", 0, 20), new Color(248,0,0));
}

3.添加效果

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值