前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >图像处理基础(五)-ffmpeg YUV转化为JPEG并保存

图像处理基础(五)-ffmpeg YUV转化为JPEG并保存

作者头像
Pulsar-V
发布2019-03-12 17:04:45
2.2K0
发布2019-03-12 17:04:45
举报
文章被收录于专栏:Pulsar-VPulsar-V
代码语言:javascript
复制
int yuv420_to_jpg(void *data,int w,int h,char *file)
{
    av_register_all();
    AVFormatContext *pFormatCtx = avformat_alloc_context();
    AVOutputFormat *fmt = av_guess_format("mjpeg", NULL, NULL);
    pFormatCtx->oformat = fmt;
    if (avio_open(&pFormatCtx->pb,file, AVIO_FLAG_READ_WRITE) < 0){
        printf("Couldn't open output file.");
        return -1;
    }
    AVStream *video_st = avformat_new_stream(pFormatCtx, 0);
    if (video_st==NULL){
        return -1;
    }
    AVCodecContext *pCodecCtx = video_st->codec;
    pCodecCtx->codec_id = fmt->video_codec;
    pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO;
    pCodecCtx->pix_fmt = PIX_FMT_YUVJ420P;
    pCodecCtx->width = w; 
    pCodecCtx->height = h;
    pCodecCtx->time_base.num = 1;
    pCodecCtx->time_base.den = 25;
    AVCodec *pCodec = avcodec_find_encoder(pCodecCtx->codec_id);
    if (!pCodec){
        return -1;
    }
    if (avcodec_open2(pCodecCtx, pCodec,NULL) < 0){
        return -1;
    }
    AVFrame *picture = av_frame_alloc();
    int size = avpicture_get_size(pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height);
    uint8_t *picture_buf = (uint8_t *)av_malloc(size);
    if (!picture_buf){
        return -1;
    }
    avpicture_fill((AVPicture *)picture, picture_buf, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height);
    avformat_write_header(pFormatCtx,NULL);
    int y_size = pCodecCtx->width * pCodecCtx->height;
    AVPacket pkt;
    av_new_packet(&pkt,y_size*3);
    memcpy(picture_buf,data,y_size*3/2);
    picture->data[0] = picture_buf;
    picture->data[1] = picture_buf+ y_size;
    picture->data[2] = picture_buf+ y_size*5/4;
    int got_picture = 0;
    int ret = avcodec_encode_video2(pCodecCtx, &pkt,picture, &got_picture);
    if(ret < 0){
        printf("Encode Error.\n");
        return -1;
    }
    if (got_picture==1){
        pkt.stream_index = video_st->index;
        ret = av_write_frame(pFormatCtx, &pkt);
    }
    av_free_packet(&pkt);
    av_write_trailer(pFormatCtx);
    if (video_st){
        avcodec_close(video_st->codec);
        av_free(picture);
        av_free(picture_buf);
    }
    avio_close(pFormatCtx->pb);
    avformat_free_context(pFormatCtx);
    return 1;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018/07/04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
图像处理
图像处理基于腾讯云深度学习等人工智能技术,提供综合性的图像优化处理服务,包括图像质量评估、图像清晰度增强、图像智能裁剪等。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档