原文地址:http://www.cnblogs.com/wanggang123/p/6707985.html

FFmpeg支持添加文字功能,具体如何将文字叠加到视频中的每一张图片,FFmpeg调用了文字库FreeSerif.ttf。当我们

用到ffmpeg 添加文字功能时 我们需要先下载改文字库,下载地址是http://www.fonts2u.com/free-serif.font,这算是

前期准备工作。准备工作完成以后,我来介绍下Ffmpeg实现视频文件添加文字功能的基本流程,流程图如下图所示:

      图1. Ffmpeg 向视频添加文字流程

Ffmpeg 以Filter的方式添加文字,下面给出具体的代码。

1. 打开视频文件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int OpenInput(char *fileName)
{
    context = avformat_alloc_context();
    context->interrupt_callback.callback = interrupt_cb;
    AVDictionary *format_opts =  nullptr;
 
    int ret = avformat_open_input(&context, fileName, nullptr, &format_opts);
    if(ret < 0)
    {
        return  ret;
    }
    ret = avformat_find_stream_info(context,nullptr);
    av_dump_format(context, 0, fileName, 0);
    if(ret >= 0)
    {
        std::cout <<"open input stream successfully" << endl;
    }
    return ret;
}

2. 初始化 初始化包括输出上下文以及Filter,解码器,编码器四个部分。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//初始化输出上下文
int OpenOutput(char *fileName)
{
    int ret = 0;
    ret  = avformat_alloc_output_context2(&outputContext, nullptr"mpegts", fileName);
    if(ret < 0)
    {
        goto Error;
    }
    ret = avio_open2(&outputContext->pb, fileName, AVIO_FLAG_READ_WRITE,nullptrnullptr);  
    if(ret < 0)
    {
        goto Error;
    }
 
    for(int i = 0; i < context->nb_streams; i++)
    {
        AVStream * stream = avformat_new_stream(outputContext, outPutEncContext->codec);
        stream->codec = outPutEncContext;
        if(ret < 0)
        {
            goto Error;
        }
    }
    av_dump_format(outputContext, 0, fileName, 1);
    ret = avformat_write_header(outputContext, nullptr);
    if(ret < 0)
    {
        goto Error;
    }
    if(ret >= 0)
        cout <<"open output stream successfully" << endl;
    return ret ;
Error:
    if(outputContext)
    {
        avformat_close_input(&outputContext);
    }
    return ret ;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
 //初始化filter<br>int InitFilter(AVCodecContext * codecContext)
{
    char args[512];
    int ret = 0;   
 
    AVFilter *buffersrc  = avfilter_get_by_name("buffer");
    AVFilter *buffersink = avfilter_get_by_name("buffersink");
    AVFilterInOut *outputs = avfilter_inout_alloc();
    AVFilterInOut *inputs  = avfilter_inout_alloc();
    string  filters_descr ="drawtext=fontfile=D\\\\:FreeSerif.ttf:fontsize=100:text=hello world:x=100:y=100";
    enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV420P};
 
    filter_graph = avfilter_graph_alloc();
    if (!outputs || !inputs || !filter_graph) {
        ret = AVERROR(ENOMEM);
        goto end;
    }
 
    /* buffer video source: the decoded frames from the decoder will be inserted here. */
    sprintf_s(args, sizeof(args),
        "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
        codecContext->width, codecContext->height, codecContext->pix_fmt,
        codecContext->time_base.num, codecContext->time_base.den,
        codecContext->sample_aspect_ratio.num, codecContext->sample_aspect_ratio.den);
 
    ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
        args, NULL, filter_graph);
    if (ret < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot create buffer source\n");
        goto end;
    }
 
    /* buffer video sink: to terminate the filter chain. */
    ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
        NULL, NULL, filter_graph);
    if (ret < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot create buffer sink\n");
        goto end;
    }
 
    ret = av_opt_set_int_list(buffersink_ctx, "pix_fmts", pix_fmts,
        AV_PIX_FMT_YUV420P, AV_OPT_SEARCH_CHILDREN);
    if (ret < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot set output pixel format\n");
        goto end;
    }
 
    /* Endpoints for the filter graph. */
    outputs->name       = av_strdup("in");
    outputs->filter_ctx = buffersrc_ctx;
    outputs->pad_idx    = 0;
    outputs->next       = NULL;
 
    inputs->name       = av_strdup("out");
    inputs->filter_ctx = buffersink_ctx;
    inputs->pad_idx    = 0;
    inputs->next       = NULL;   
    if ((ret = avfilter_graph_parse_ptr(filter_graph, filters_descr.c_str(),
        &inputs, &outputs, NULL)) < 0)
        goto end;
 
    if ((ret = avfilter_graph_config(filter_graph, NULL)) < 0)
        goto end;
    return ret;
end:
    avfilter_inout_free(&inputs);
    avfilter_inout_free(&outputs);
    return ret;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
//初始化编码器<br>int InitEncoderCodec( int iWidth, int iHeight)
{
    AVCodec *  pH264Codec = avcodec_find_encoder(AV_CODEC_ID_H264);
    if(NULL == pH264Codec)
    {
        printf("%s""avcodec_find_encoder failed");
        return  -1;
    }
    outPutEncContext = avcodec_alloc_context3(pH264Codec);
    outPutEncContext->gop_size = 30;
    outPutEncContext->has_b_frames = 0;
    outPutEncContext->max_b_frames = 0;
    outPutEncContext->codec_id = pH264Codec->id;
    outPutEncContext->time_base.num =context->streams[0]->codec->time_base.num;
    outPutEncContext->time_base.den = context->streams[0]->codec->time_base.den;
    outPutEncContext->pix_fmt            = *pH264Codec->pix_fmts;
    outPutEncContext->width              =  iWidth;
    outPutEncContext->height             = iHeight;
 
    outPutEncContext->me_subpel_quality = 0;
    outPutEncContext->refs = 1;
    outPutEncContext->scenechange_threshold = 0;
    outPutEncContext->trellis = 0;
    AVDictionary *options = nullptr;
    outPutEncContext->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
 
    int ret = avcodec_open2(outPutEncContext, pH264Codec, &options);
    if (ret < 0)
    {
        printf("%s""open codec failed");
        return  ret;
    }
    return 1;
}
<br>//初始化解码器
int InitDecodeCodec(AVCodecID codecId)
{
    auto codec = avcodec_find_decoder(codecId);
    if(!codec)
    {
        return -1;
    }
    decoderContext = context->streams[0]->codec;
    if (!decoderContext) {
        fprintf(stderr, "Could not allocate video codec context\n");
        exit(1);
    }
 
    if (codec->capabilities & AV_CODEC_CAP_TRUNCATED)
        decoderContext->flags |= AV_CODEC_FLAG_TRUNCATED;
    int ret = avcodec_open2(decoderContext, codec, NULL);
    return ret;
 
}

源码地址:http://pan.baidu.com/s/1o8Lkozw

视频地址:http://pan.baidu.com/s/1jH4dYN8

FFmpeg 向视频中添加文字的更多相关文章

  1. php使用ffmpeg向视频中添加文字字幕

    这篇文章主要介绍了PHP使用ffmpeg给视频增加字幕显示的方法,实例分析了php操作ffmpeg给视频增加字母的技巧,具有一定参考借鉴价值,需要的朋友可以参考下. 本文实例讲述了PHP使用ffmpe ...

  2. Ffmpeg 视频教程 向视频中添加文字

    Ffmpeg支持添加文字功能,具体如何将文字叠加到视频中的每一张图片,FFmpeg调用了文字库FreeSerif.ttf.当我们 用到ffmpeg 添加文字功能时 我们需要先下载改文字库,下载地址是h ...

  3. WPF 在绘图控件(Shape)中添加文字 [2018.7.15]

    原文:WPF 在绘图控件(Shape)中添加文字 [2018.7.15] Q:使用Shape的子类Ellipse画一个圆,如何在圆中添加文字? A:Shape类中不包含Text属性.可使用Shape类 ...

  4. OSG项目经验2<在场景中添加文字面版>

    添加文字版需要用到osg的三个名字空间:                         osgText::Text,这个类用来添加文字和设置文字的一些属性:                     ...

  5. mp4视频中插入文字

    最近接到一个需求,需要往mp4中动态插入文字,并且mp4中的乌云能在文字上有飘动的效果,一开始想用canvas,但是由于本人经验不足,没什么思路,看到css3有一个属性:mix-blend-mode, ...

  6. WPF中RichTextBox中添加文字的两种方法

    RichTextBox控件不同于TextBox控件,后者可以直接通过其Text属性绑定或者在后台动态添加文字. (一)使用数据绑定 <RichTextBox FontSize="12& ...

  7. vue中添加文字或图片水印

    首先引用warterMark.js,内容如下 'use strict' var watermark = (className,str,type) => { let dom = document. ...

  8. “display:block-inline形式的Span或Div中添加文字后,导致Span或Div排版掉落、错位”的原因及解决方法

    最近在使用3个span(或div)制作带圆角边框的按钮时,按照常识,把span的display设置成inline-block,这样就可以设置span的width和height了,很爽的~ 可是当我在中 ...

  9. 关于three.js中添加文字的方式[转]

    https://blog.csdn.net/qq563969790/article/details/76584976 网上资料大部分是通过引入外部font库进行文字效果的载入,但是在实际运行的时候发现 ...

随机推荐

  1. maven 指定工程的 jdk 版本及编译级别

    <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> ...

  2. BFC与hasLayout

    BFC与hasLayout都是CSS布局上的概念. 几个月前在微博上才了解什么是BFC,算是对布局有点初步的了解. hasLayout则是IE6.7产生许多bug的根源. 一.BFC Floats, ...

  3. 64位系统下同时使用64位和32位的eclipse

    eclipse.ini 文件使用说明 The -vm option and its value (the path) must be on separate lines. The value must ...

  4. ffmpeg的IO操作

    ffmpeg 可以通过IO操作将数据读取和存储在文件或网络中 作为数据的读取和写入地址,数据被存放在file,http, ffmpeg 不仅可以编解常用的音视频格式,还可以将数据导入/导出到各种媒介中 ...

  5. appium+python自动化98-非select弹出选择框定位解决

    前言 遇到问题:document.getElementsByClassName(...)[0] is undefined 选择框如果是select标签的,可以直接用select专用的方法去定位点击操作 ...

  6. 支持向量机通俗导论(理解SVM的三层境界) by v_JULY_v

    支持向量机通俗导论(理解SVM的三层境界) 前言 动笔写这个支持向量机(support vector machine)是费了不少劲和困难的,原因很简单,一者这个东西本身就并不好懂,要深入学习和研究下去 ...

  7. WCF项目中出现“目标程序集不包含服务类型”的解决办法

    如果创建新项目时(以下简称A项目)选择的是WCF相关的项目模板,并且在A项目中只定义接口而不实现接口,那么任何引用了A项目的项目,在调试时都会弹出警告框“目标程序集不包含服务类型.可能需要调整此程序集 ...

  8. java中遍历实体类属性和类型

    public static void testReflect(Object model) throws NoSuchMethodException, IllegalAccessException, I ...

  9. 使用webService时,gsoap数据类型注意事项

    今天在使用gsoap生成webservice客户端文件时,发现我的参数类型全被改了,比如string型变成了char*,原来有STL的地方也变没了,经过研究发现,原来和我生成的头文件时使用的参数有关, ...

  10. FormBorderStyle为None的时候如何拖动窗体

    //为DllImport导出命名空间, using System.Runtime.InteropServices; public partial class Form1 : System.Window ...