SoFunction
Updated on 2025-03-03

Java ffmpeg implements video plus text/image watermark function (sample code)

Java ffmpeg implements video plus text/image watermark function (sample code)

Updated: October 25, 2024 09:17:26 Author: menghl
This article introduces the method of using Java and ffmpeg libraries to implement video adding text or image watermarks. By introducing dependency code and examples, it explains in detail how to add text watermarks and image watermarks to the video, providing practical guidance for developers who need to add watermarks to the video. This method not only enhances the copyright protection of video content, but also provides more possibilities for video editing.

Introduce dependencies

<dependency>
  <groupId></groupId>
  <artifactId>javacv-platform</artifactId>
  <version>1.5.4</version>
</dependency>
<dependency>
  <groupId></groupId>
  <artifactId>ffmpeg-platform</artifactId>
  <version>4.3.1-1.5.4</version>
</dependency>

Code Example

Text watermark implementation

import .*;
import ;

import .*;
import ;

/**
  * Add text watermark to video
  *
  * @author alin
  */
public class VideoWatermark {

    public static void main(String[] args) throws Exception {
        // Video file        String inputFile = "D:\\test\\video.mp4";
        // Output file        String outputFile = "D:\\test\\output.mp4";

        // Initialize FFmpegFrameGrabber to read the input video file        try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputFile)) {
            ();
            // Initialize FFmpegFrameRecorder to write output video file            try (FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputFile, (), (), ())) {
                ("mp4");
                (());
                (());
                (());
                (());
                (());
                ();

                // Process every frame                Frame frame;
                Java2DFrameConverter converter = new Java2DFrameConverter();
                while ((frame = ()) != null) {
                    if ( != null) {
                        // Convert Frame to BufferedImage                        BufferedImage bufferedImage = (frame);

                        // Draw text watermark on BufferedImage                        Graphics2D g = ();
                        // Enable anti-aliasing                        (RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                        // Enable text anti-aliasing                        (RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                        // Use Chinese-supported fonts                        (new Font("Microsoft YaHei", , 30));
                        ();
                        String watermarkText = "Test watermark text";

                        // Calculate the position of the watermark text in the lower right corner                        //FontMetrics fontMetrics = ();
                        //int textWidth = (watermarkText);
                        //int textHeight = ();
                        //int x = () - textWidth - 10; // Right margin 10 pixels                        //int y = () - textHeight + () - 10; // The bottom margin is 10 pixels
                        // Calculate the position of the watermark text in the upper left corner                        int x = 10; // 10 pixels left margin                        int y = 30; // Top margin is 30 pixels
                        (watermarkText, x, y);
                        ();

                        // Convert BufferedImage back to Frame                        frame = (bufferedImage);
                    }

                    // Record frames                    (frame);
                }
                // Close grabber and recorder                ();
                ();
                ();
            }
        }
    }
}

Image watermark implementation

import .*;
import ;
import ;
import .*;
import ;
import ;
import ;
import ;
/**
  * Add image watermark to video
  *
  * @author alin
  */
public class VideoWatermark {
    public static void main(String[] args) throws Exception {
        // Video file        String inputFile = "D:\\test\\video.mp4";
        // Output file        String outputFile = "D:\\test\\output.mp4";
        // Watermark photos        String watermarkImageUrl = "D:\\test\\";
        try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputFile)) {
            ();
            try (FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputFile, (), (), ())) {
                ("mp4");
                (());
                (());
                (());
                (());
                (());
                ();
                BufferedImage watermarkImage = loadWatermarkImage(watermarkImageUrl);
                Frame frame;
                while ((frame = ()) != null) {
                    if ( != null) {
                        Java2DFrameConverter converter = new Java2DFrameConverter();
                        BufferedImage bufferedImage = (frame);
                        // Draw image watermark on BufferedImage                        Graphics2D g = ();
                        ((AlphaComposite.SRC_OVER, 0.5f));
                        int x = 10; // 10 pixels left margin                        int y = 30; // Top margin is 30 pixels                        (watermarkImage, x, y, null);
                        ();
                        frame = (bufferedImage);
                    }
                    (frame);
                }
                ();
                ();
                ();
            }
        }
    }
    /**
      * Loading watermark image
      *
      * @param imagePath Watermark image path
      * @return Watermark Picture
      * @throws IOException
      */
    private static BufferedImage loadWatermarkImage(String imagePath) throws IOException {
        //return (new URL(imagePath));
        return (new File(imagePath));
    }
}

This is the article about Java ffmpeg implementing the video plus text/picture watermark function. For more related Java ffmpeg video plus text content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!

  • Java
  • ffmpeg
  • video
  • Word

Related Articles

  • Detailed analysis of Semaphore counting semaphore in Java

    This article mainly introduces the detailed analysis of Semaphore counting semaphore in Java. Semaphore is a counting semaphore that must be released by the thread that obtains it. It is often used to limit the number of threads that can access certain resources. For example, through Semaphore, current limiting, friends who need it can refer to it.
    2023-11-11
  • Detailed explanation of the instance of createStatement() method in java

    This article mainly introduces the detailed explanation of the createStatement() method in java. Friends who need it can refer to it
    2017-06-06
  • Maven dependency conflict loading order and resolution

    This article mainly introduces the different versions of the same dependency cited in the project, that is, conflict, how maven is selected. It understands how it helps solve the dependency problems in the project. Friends who need it can refer to it
    2024-01-01
  • Proficient in Java List Extract objects by field

    This article mainly introduces the relevant information about extracting objects by field by proficient in Java List. Friends who need it can refer to it
    2023-11-11
  • Spring Boot Integration Swagger2 Build API Documentation

    This article mainly introduces the API document that integrates Swagger2. By using Swagger, we only need to define the interface and the relevant information of the interface according to the series of specifications given by it, and then it can help us automatically generate interface documents in various formats, which facilitates front-end and back-end developers to conduct front-end and back-end joint debugging. Friends who need it below can refer to it.
    2022-03-03
  • After java Date is installed as an English String, the solution cannot be returned to Date

    This article introduces the solution that after Java Date is installed as a String in English, it cannot be turned back to Date. It has certain reference value, let's take a look with the editor below
    2017-01-01
  • Detailed explanation of Java object deep copy and shallow copy instances

    This article mainly introduces the relevant information about the detailed explanation of Java object deep copy and shallow copy instances. Friends who need it can refer to it
    2017-05-05
  • Detailed explanation of the difference between

    There are two Date classes in Java. One is usually used to obtain the current time or construct the time, and the other is used for SQL statements. It only contains dates but does not have the time part. This article mainly introduces relevant information about the differences. Friends who need it can refer to it.
    2023-03-03
  • MyBatis cache function principle and instance analysis

    This article mainly introduces the principle of MyBatis cache function and example analysis. The example code is introduced in this article in detail, which has certain reference value for everyone's learning or work. Friends who need it can refer to it.
    2020-03-03
  • Detailed explanation of JAVA implementation of Huffman Tree

    The so-called Huffman tree requires the minimum weighted path length. What does this mean? In short, it is necessary to multiply the path length (height -1) corresponding to all nodes by the weight of the node, and then ensure that the sum of these results is minimized. The following article will introduce you in detail
    2016-08-08

Latest Comments