Home > Java > javaTutorial > body text

How to add text watermark and picture watermark function in Java

王林
Release: 2023-05-23 08:56:12
forward
1716 people have browsed it

    Add watermark

    The main purpose of adding watermarks to pictures is to protect the copyright of the pictures to prevent unauthorized people from using or Spread this image. Adding watermarks to images is a common image processing technique. You can use the Graphics2D class that comes with Java JDK to draw watermarks. You can add image watermarks or text watermarks.

    The Java platform provides a Java 2D API class library for implementing 2D image drawing. The software provides support for multiple image, font, and color management formats and comes with many advanced features such as alpha blending, depth buffer, and more.

    Introduction to Java 2D API

    1. Create an object for drawing graphics

    Use the Graphics2D class to create an object for drawing graphics. More drawing functions can be achieved by extending the Graphics2D object, a subclass of the Graphics class.

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

    2. Draw basic graphics

    Java 2D API supports drawing various basic 2D graphics, such as line segments, rectangles, ellipses, arcs, etc.

    // 绘制一条线段
    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);
    Copy after login

    3. Draw text

    You can use the drawString() method of the Graphics2D object to draw string text on the image

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

    4. Draw the image

    Supports loading and drawing images in various formats, such as JPEG, PNG, GIF, etc. You can also use the ImageIO class to load an image file and draw it onto the image using the drawImage() method of the Graphics2D object.

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

    5. Set drawing properties

    You can use the set method of the Graphics2D object to set various drawing properties, such as color, font, line width, etc.

    // 设置绘制颜色为红色
    g2d.setColor(Color.RED);
    // 设置字体为 Arial,大小为 24
    g2d.setFont(new Font("Arial", Font.PLAIN, 24));
    // 设置线宽为 3 像素
    g2d.setStroke(new BasicStroke(3));
    Copy after login

    Draw text watermark

    To add a text watermark to an image, the steps are as follows:

    • Use the ImageIO class to load the watermark that needs to be added Image

    • Create a custom image object of BufferedImage and use the Graphics2D object to draw the original image onto the object

    • Create a font object, And set the font, color, transparency and other attributes

    • Use the drawString() method of the Graphics2D object to draw the string at the location where the watermark needs to be added

    • Use the ImageIO class to save the modified image to the specified directory

        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();
            }
        }
    Copy after login
        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);
        }
    Copy after login

    Draw a picture watermark

    To add a picture watermark to the picture, the steps are as follows:

    • Use the ImageIO class to load images that need to be watermarked

    • Create a custom image object of BufferedImage, and use the Graphics2D object to draw the original image to the object

    • Use the ImageIO class to load the watermark image and set the transparency and other properties

    • Draw the watermark image and release related resources

    • Use the ImageIO class to save the modified image to the specified directory

        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();
            }
        }
    Copy after login
        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);
        }
    Copy after login

    Add text watermark in a loop

    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;
        }
    }
    Copy after login
        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);
        }
    Copy after login

    The above is the detailed content of How to add text watermark and picture watermark function in Java. For more information, please follow other related articles on the PHP Chinese website!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template