Ffmpeg 如何为视频加水印,c++纯代码实现
时间: 2023-03-22 07:01:04 浏览: 291
Ffmpeg是一个功能强大的视频处理工具,可以通过在视频中添加水印来保护视频内容的版权,以下是使用C语言实现在视频中添加水印的步骤:
1.打开视频文件
```c
AVFormatContext *fmt_ctx = avformat_alloc_context();
if(avformat_open_input(&fmt_ctx, "input.mp4", NULL, NULL) < 0) {
printf("无法打开输入文件\n");
exit(1);
}
```
2.查找视频流
```c
if(avformat_find_stream_info(fmt_ctx, NULL) < 0) {
printf("无法查找视频流信息\n");
exit(1);
}
int video_index = -1;
for(int i=0; i<fmt_ctx->nb_streams; i++) {
if(fmt_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
video_index = i;
break;
}
}
if(video_index == -1) {
printf("无法找到视频流\n");
exit(1);
}
AVCodecParameters *codec_par = fmt_ctx->streams[video_index]->codecpar;
```
3.打开视频解码器
```c
AVCodec *codec = avcodec_find_decoder(codec_par->codec_id);
if(codec == NULL) {
printf("无法找到解码器\n");
exit(1);
}
AVCodecContext *codec_ctx = avcodec_alloc_context3(codec);
if(avcodec_parameters_to_context(codec_ctx, codec_par) < 0) {
printf("无法将解码器参数转换为上下文\n");
exit(1);
}
if(avcodec_open2(codec_ctx, codec, NULL) < 0) {
printf("无法打开解码器\n");
exit(1);
}
```
4.创建输出文件
```c
AVFormatContext *out_fmt_ctx = NULL;
if(avformat_alloc_output_context2(&out_fmt_ctx, NULL, NULL, "output.mp4") < 0) {
printf("无法创建输出文件\n");
exit(1);
}
AVStream *out_stream = avformat_new_stream(out_fmt_ctx, codec);
if(out_stream == NULL) {
printf("无法创建输出流\n");
exit(1);
}
if(avcodec_parameters_copy(out_stream->codecpar, codec_par) < 0) {
printf("无法复制编解码器参数\n");
exit(1);
}
if(avio_open(&out_fmt_ctx->pb, "output.mp4", AVIO_FLAG_WRITE) < 0) {
printf("无法打开输出文件\n");
exit(1);
}
if(avformat_write_header(out_fmt_ctx, NULL) < 0) {
printf("无法写入输出文件头\n");
exit(1);
}
```
5.创建水印
```c
AVFilterContext *buffersrc_ctx;
AVFilterContext *buffersink_ctx;
AVFilterGraph *filter_graph;
const char *filter_descr = "movie=watermark.png[watermark];[in][watermark]overlay=x=100:y=100[out]";
avfilter_register_all();
AVFilter *buffersrc = avfilter_get_by_name("buffer");
AVFilter *buffersink = avfilter_get_by_name("buffersink");
AVFilterInOut *outputs = avfilter_inout_alloc();
AVFilterInOut *inputs = avfilter_inout_alloc();
enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUV420P, AV_PIX_FMT
阅读全文
相关推荐


















