二、添加文字水印
创建命令行参数
确定输入视频文件路径、输出视频文件路径、文字内容、字体大小、字体颜色等参数。
输入视频:inputVideo.mp4
输出视频:outputVideoWithText.mp4
文字内容:“水印文字”
字体大小:50
字体颜色:白色。
构建 FFmpeg 命令
使用以下命令格式添加文字水印:
-i inputVideo.mp4
:指定输入视频文件。
-vf "drawtext=text='水印文字':fontsize=50:fontcolor=white:x=10:y=10"
:使用视频滤镜,这里设置了文字水印的参数,包括文字内容、字体大小、颜色和位置。
outputVideoWithText.mp4
:指定输出视频文件。
在 Java 中,可以使用 Runtime.getRuntime ().exec () 方法来执行命令行命令。但这种方法较为复杂,推荐使用 JavaCV 等库来简化操作。
三、添加图片水印
创建命令行参数
确定输入视频文件路径、输出视频文件路径、图片水印文件路径、水印位置等参数。
输入视频:inputVideo.mp4
输出视频:outputVideoWithImage.mp4
图片水印:watermark.png
水印位置:x=10,y=10。
构建 FFmpeg 命令
使用以下命令格式添加图片水印:
-i inputVideo.mp4
:指定输入视频文件。
-i watermark.png
:指定图片水印文件。
-filter_complex "overlay=x=10:y=10"
:使用复杂滤镜,将图片水印覆盖在视频上,设置水印位置为 x=10,y=10。
outputVideoWithImage.mp4
:指定输出视频文件。
同样,可以使用 JavaCV 等库来执行这个命令。
以下是一个使用 JavaCV 实现添加文字水印的示例代码:
import org.bytedeco.ffmpeg.global.avutil;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.Frame;
public class VideoWatermarkingExample {
public static void addTextWatermark(String inputVideoPath, String outputVideoPath, String text, int fontSize, String fontColor, int xPosition, int yPosition) {
try {
FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputVideoPath);
grabber.start();
FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputVideoPath, grabber.getImageWidth(), grabber.getImageHeight());
recorder.setVideoCodec(grabber.getVideoCodec());
recorder.setFormat(grabber.getFormat());
recorder.setFrameRate(grabber.getFrameRate());
recorder.start();
Frame frame;
while ((frame = grabber.grabFrame())!= null) {
// 添加文字水印
recorder.record(frame, "drawtext=text='" + text + "':fontsize=" + fontSize + ":fontcolor=" + fontColor + ":x=" + xPosition + ":y=" + yPosition);
grabber.stop();
recorder.stop();
} catch (Exception e) {
e.printStackTrace();
public static void main(String[] args) {
String inputVideoPath = "inputVideo.mp4";
String outputVideoPath = "outputVideoWithText.mp4";
String text = "水印文字";
int fontSize = 50;
String fontColor = "white";
int xPosition = 10;
int yPosition = 10;
addTextWatermark(inputVideoPath, outputVideoPath, text, fontSize, fontColor, xPosition, yPosition);