说明:
由于android原生的YuvImage.compressToJpeg()可能存在内存泄漏的情况,此处使用ffmpeg将yuv数据帧直接保存为jpeg图片。
输入:yuv数据,由camera采集的nv21数据
输出:jpeg图片
由于此处采样的是nv21数据,而最终保存的是YUVJ420P,因而需要对数据进行转换;若是输入为其它格式,则做相应的转换。
具体如下:
1.yuv帧转jpg图片:
/**
* @param dt 数据帧
* @param w 图片width
* @param h 图片height
* @param file 图片存储地址
*/
int JpegParser::yuv2jpg(uint8_t *dt, int w, int h, const char *file) {
LOG_E("yuv to jpg start.")
av_register_all();
AVFormatContext *formatContext;
avformat_alloc_output_context2(&formatContext, NULL, NULL, file);
LOG_E("yuv to jpg:%s", formatContext->oformat->name)
if(avio_open(&formatContext->pb, file, AVIO_FLAG_WRITE) < 0){
LOG_E("open file fail:%s", file)
return -1;
}
const char * codec_name = "mjpeg";
AVCodec *avCodec = avcodec_find_encoder_by_name(codec_name);
if(!avCodec){
LOG_E("找不到编码器")
return -1;
}
LOG_E("find encoder:%s", avCodec->name)
AVStream *avStream = avformat_new_stream(formatContext, avCodec);
if(avStream == NULL){
LOG_E("new av stream fail.")
return -1