第28月第18天 ffmpeg jpg

1.

/**
 * 将AVFrame(YUV420格式)保存为JPEG格式的图片
 *
 * @param width YUV420的宽
 * @param height YUV42的高
 *
 */
int MyWriteJPEG(AVFrame* pFrame, int width, int height, int iIndex)
{
// 输出文件路径
char out_file[MAX_PATH] = {0};
 
 
//   sprintf_s(out_file, sizeof(out_file), "./%d.jpg",  iIndex);
 
sprintf(out_file,"./tupian/%d.jpg",iIndex);
 
// 分配AVFormatContext对象
AVFormatContext* pFormatCtx = avformat_alloc_context();
 
// 设置输出文件格式
pFormatCtx->oformat = av_guess_format("mjpeg", NULL, NULL);
 
// 创建并初始化一个和该url相关的AVIOContext
if( avio_open(&pFormatCtx->pb, out_file, AVIO_FLAG_READ_WRITE) < 0)
{
printf("Couldn't open output file.");
return -1;
}
 
 
// 构建一个新stream
AVStream* pAVStream = avformat_new_stream(pFormatCtx, 0);
if( pAVStream == NULL )
{
return -1;
}
 
 
// 设置该stream的信息
AVCodecContext* pCodecCtx = pAVStream->codec;
 
pCodecCtx->codec_id = pFormatCtx->oformat->video_codec;
pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO;
pCodecCtx->pix_fmt = PIX_FMT_YUVJ420P;
pCodecCtx->width = width;
pCodecCtx->height = height;
pCodecCtx->time_base.num = 1;
pCodecCtx->time_base.den = 25;
 
// Begin Output some information
av_dump_format(pFormatCtx, 0, out_file, 1);
// End Output some information
 
 
// 查找解码器
AVCodec* pCodec = avcodec_find_encoder(pCodecCtx->codec_id);
if( !pCodec )
{
printf("Codec not found.");
return -1;
}
// 设置pCodecCtx的解码器为pCodec
if( avcodec_open2(pCodecCtx, pCodec, NULL) < 0 ) 
{
printf("Could not open codec.");
return -1;
}
 
 
//Write Header
avformat_write_header(pFormatCtx, NULL);
 
 
int y_size = pCodecCtx->width * pCodecCtx->height;
 
 
//Encode
// 给AVPacket分配足够大的空间
AVPacket pkt;
av_new_packet(&pkt, y_size * 3);
 
 
// 
int got_picture = 0;
int ret = avcodec_encode_video2(pCodecCtx, &pkt, pFrame, &got_picture);
if( ret < 0 )
{
printf("Encode Error.\n");
return -1;
}
printf("got_picture %d \n",got_picture);
if( got_picture == 1 )
{
//pkt.stream_index = pAVStream->index;
ret = av_write_frame(pFormatCtx, &pkt);
}
 
 
av_free_packet(&pkt);
 
 
//Write Trailer
av_write_trailer(pFormatCtx);
 
 
printf("Encode Successful.\n");
 
 
if( pAVStream )
{
avcodec_close(pAVStream->codec);
}
 
avio_close(pFormatCtx->pb);
avformat_free_context(pFormatCtx);
 
 
return 0;
}

https://blog.csdn.net/charleslei/article/details/51084046

https://blog.csdn.net/xiaoliumo/article/details/78852254

猜你喜欢

转载自www.cnblogs.com/javastart/p/10286204.html