Java实现添加文字水印、图片水印功能

添加水印

为图片添加水印的主要作用是保护图片版权,防止图片被未经授权的人使用或传播。为图片添加水印是一种常用的图片处理技术。在Java 中可以使用JDK自带的 Graphics2D 类来绘制水印。可以添加图片水印或者文字水印。

Java 2D API是Java 平台上用于绘制 2D 图形的一组类和方法。它支持多种格式的图像、字体和颜色管理,并提供了许多高级特性,如 alpha 融合、深度缓冲区等。

Java 2D API介绍

1.创建一个绘制图形的对象

使用Graphics2D 类来创建一个绘制图形的对象。Graphics2D 对象是扩展了 Graphics 类的一个子类,提供了更多的绘制功能。

// 创建一个大小为 800x600 像素的空白图像
BufferedImage image = new BufferedImage(800, 600, BufferedImage.TYPE_INT_ARGB);
// 递给 Graphics2D 对象以进行绘制操作
Graphics2D g2d = image.createGraphics();
复制代码

2.绘制基本图形

Java 2D API 支持绘制各种基本的 2D 图形,例如线段、矩形、椭圆、弧形等

// 绘制一条线段
g2d.drawLine(100, 100, 200, 200);

// 绘制一个矩形
g2d.drawRect(300, 100, 100, 50);

// 绘制一个椭圆
g2d.drawOval(500, 100, 100, 150);

// 绘制一个弧形
g2d.drawArc(100, 300, 100, 100, 0, 90);
复制代码

3.绘制文本

可以使用 Graphics2D 对象的 drawString() 方法来在图像上绘制字符串文本

// 将字符串 "Hello, Java 2D!" 绘制在坐标 (200, 400) 处
g2d.drawString("Hello, Java 2D!", 200, 400);
复制代码

4.绘制图像

支持加载和绘制各种格式的图像,例如 JPEG、PNG、GIF 等。还可以使用 ImageIO 类加载图像文件,并使用 Graphics2D 对象的 drawImage() 方法将其绘制到图像上。

// 从指定的文件路径加载一张图片,并将其绘制在图像的左上角
BufferedImage image = ImageIO.read(new File("image.jpg"));
g2d.drawImage(image, 0, 0, null);
复制代码

5.设置绘制属性

可以使用 Graphics2D 对象的 set 方法来设置多种绘制属性,例如颜色、字体、线宽等。

// 设置绘制颜色为红色
g2d.setColor(Color.RED);

// 设置字体为 Arial,大小为 24
g2d.setFont(new Font("Arial", Font.PLAIN, 24));

// 设置线宽为 3 像素
g2d.setStroke(new BasicStroke(3));
复制代码

绘制文字水印

对图片添加文字水印,执行步骤操作如下:

使用ImageIO类加载需要添加水印的图片

创建一个BufferedImage的自定义图像对象,并使用Graphics2D对象将原始图像绘制到该对象上

创建字体对象,并设置字体、颜色、透明度等属性

使用Graphics2D对象的drawString()方法在需要添加水印的位置绘制字符串

使用ImageIO类将修改后的图像保存到指定目录
复制代码
    public static void addWatermark(File input, File out, String text, int fontSize) {
        // 读取原图片
        BufferedImage image = null;
        try {
            image = ImageIO.read(input);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 获取图片的宽度和高度
        int width = image.getWidth();
        int height = image.getHeight();
        
        // 创建一个图片缓存对象
        BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 获取图片的画笔
        Graphics2D g = newImage.createGraphics();
        // 将原图片绘制到缓存图片上
        g.drawImage(image, 0, 0, width, height, null);
        
        // 创建字体对象
        Font font = new Font("微软雅黑", Font.BOLD, fontSize);
        // 创建字体渲染上下文
        FontRenderContext frc = new FontRenderContext(null, true, true);
        // 计算字符串的宽度和高度
        Rectangle2D bounds = font.getStringBounds(text, frc);
        // 字符宽度
        int strWidth = (int) bounds.getWidth();
        // 字符高度
        int strHeight = (int) bounds.getHeight();

        // 设置水印的字体样式
        g.setFont(font);
        // 设置水印的颜色
        g.setColor(Color.red);
        // 设置水印的位置 根据需要再自行调整宽度、高度
        g.drawString(text, width - strWidth - 10, height - strHeight + 15);
        // 释放图形上下文使用的系统资源
        g.dispose();
        
        // 保存带水印的图片
        try {
            ImageIO.write(newImage, "png", out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
复制代码
    public static void main(String[] args) {
        File input = new File("D://test.png");
        File out = new File("D://watermark.png");
        // 水印文本内容,中文转Unicode
        String text = "\u6dfb\u52a0\u6c34\u5370";
        addWatermark(input, out, text, 20);
    }
复制代码

绘制图片水印

对图片添加图片水印,执行步骤操作如下:

使用ImageIO类加载需要添加水印的图片

创建一个BufferedImage的自定义图像对象,并使用Graphics2D对象将原始图像绘制到该对象上

使用ImageIO类加载水印图片,并设置透明度等属性

绘制水印图片,释放相关资源

使用ImageIO类将修改后的图像保存到指定目录
复制代码
    public static void addWatermark(File input, File out, File watermarkImage) {
        // 读取添加水印的图片
        BufferedImage image = null;
        try {
            image = ImageIO.read(input);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 获取图片的宽度和高度
        int width = image.getWidth();
        int height = image.getHeight();
        
        // 创建一个图片缓存对象
        BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 获取图片的画笔
        Graphics2D g = newImage.createGraphics();
        // 将原图片绘制到缓存图片上
        g.drawImage(image, 0, 0, width, height, null);
        
        // 读取水印图片
        BufferedImage watermark = null;
        try {
            watermark = ImageIO.read(watermarkImage);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 获取水印图片的宽度和高度
        int wmWidth = watermark.getWidth();
        int wmHeight = watermark.getHeight();
        
        // 设置水印图片的透明度
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f));
        // 绘制水印图片
        g.drawImage(watermark, width - wmWidth - 10, height - wmHeight - 10, wmWidth, wmHeight, null);
        // 释放图形上下文使用的系统资源
        g.dispose();
        
        // 保存带水印的图片
        try {
            ImageIO.write(newImage, "png", out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
复制代码
    public static void main(String[] args) {
        File input = new File("D://test.png");
        File out = new File("D://watermark.png");
        File watermarkImage = new File("D://watermarkImage .png");
        addWatermark(input, out, watermarkImage);
    }
复制代码

循环添加文字水印

public class AddWatermarkUtils {

    // 水印字体
    private static final Font FONT = new Font("微软雅黑", Font.PLAIN, 24);

    // 透明度
    private static final AlphaComposite COMPOSITE = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f);

    // 水印之间的间隔
    private static final int X_MOVE = 150;

    // 水印之间的间隔
    private static final int Y_MOVE = 200;

    public static void markWithContent(String inputImgPath, Font font, Color markContentColor,
                                       String waterMarkContent,
                                       String outImgPath) throws IOException {

        // 读取原图片信息
        File srcFile = new File(inputImgPath);
        File outFile = new File(outImgPath);
        BufferedImage srcImg = ImageIO.read(srcFile);

        // 图片宽、高
        int imgWidth = srcImg.getWidth();
        int imgHeight = srcImg.getHeight();

        // 图片缓存
        BufferedImage bufImg = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);

        // 创建绘图工具
        Graphics2D graphics = bufImg.createGraphics();

        // 画入原始图像
        graphics.drawImage(srcImg, 0, 0, imgWidth, imgHeight, null);

        // 设置水印颜色
        graphics.setColor(markContentColor);

        // 设置水印透明度
        graphics.setComposite(COMPOSITE);

        // 设置倾斜角度
        graphics.rotate(Math.toRadians(-35), (double) bufImg.getWidth() / 2,
                (double) bufImg.getHeight() / 2);

        // 设置水印字体
        graphics.setFont(font);

        // 消除java.awt.Font字体的锯齿
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        int xCoordinate = -imgWidth / 2, yCoordinate;
        // 字体长度
        int markWidth = FONT.getSize() * getTextLength(waterMarkContent);
        // 字体高度
        int markHeight = FONT.getSize();

        // 循环添加水印
        while (xCoordinate < imgWidth * 1.5) {
            yCoordinate = -imgHeight / 2;
            while (yCoordinate < imgHeight * 1.5) {
                graphics.drawString(waterMarkContent, xCoordinate, yCoordinate);
                yCoordinate += markHeight + Y_MOVE;
            }
            xCoordinate += markWidth + X_MOVE;
        }

        // 释放画图工具
        graphics.dispose();

        try (FileOutputStream fos = new FileOutputStream(outFile)) {
            // 输出图片
            ImageIO.write(bufImg, "jpg", fos);
            fos.flush();
        }
    }


    /**
     * 计算水印文本长度
     * 中文长度即文本长度
     * 英文长度为文本长度二分之一
     */
    public static int getTextLength(String text) {
        //水印文字长度
        int length = text.length();

        for (int i = 0; i < text.length(); i++) {
            String s = String.valueOf(text.charAt(i));
            if (s.getBytes().length > 1) {
                length++;
            }
        }
        length = length % 2 == 0 ? length / 2 : length / 2 + 1;
        return length;
    }
}

复制代码
    public static void main(String[] args) throws IOException {
        // 输入图片路径
        String inputFile = "D://test.png";
        // 输出图片路径
        String outputFile = "D://watermark.png";
        // 水印文本内容,中文转Unicode
        String watermarkText = "\u6dfb\u52a0\u6c34\u5370";
        AddWatermarkUtils.markWithContent(inputFile, FONT, Color.darkGray, watermarkText, outputFile);
    }
复制代码

作者:CodeDevMaster
链接:https://juejin.cn/post/7228608576875462713

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值