本机摄像头可直接输出mjpeg格式, 将摄像头采集的数据保存为jpg图片即可。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include "avformat.h"
#include "avcodec.h"
#include "avdevice.h"
const char* input_name= "video4linux2";
const char* file_name = "/dev/video0";
const char* out_file = "output.jpg";
int main(int argc, char * argv[])
{
AVFormatContext *fmtCtx = NULL;
AVPacket *packet;
AVInputFormat *inputFmt;
FILE *fp;
int ret;
avdevice_register_all();
if( (inputFmt = av_find_input_format (input_name)) == NULL){
printf("av_find_input_format failed\n");
return -1;
}
if (avformat_open_input ( &fmtCtx, file_name, inputFmt, NULL) < 0){
printf("avformat_open_input failed\n");
return -1;
}
av_dump_format(fmtCtx, 0, file_name, 0);
packet = (AVPacket *)av_malloc(sizeof(AVPacket));
av_read_frame(fmtCtx, packet);
fp = fopen(out_file, "wb");
if (fp < 0) {
printf("open frame data file failed\n");
return -1;
}
fwrite(packet->data, 1, packet->size, fp);
fclose(fp);
av_packet_free(&packet);
avformat_close_input(&fmtCtx);
return 0;
}
编译: gcc main.c -I/usr/local/include -lavformat -lavdevice -lavcodec -lavutil