目录
1 main.cpp
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "jpeglib.h"
int clipNv12ToJpgFile(const char *pFileName,
unsigned char* pYUVBuffer, const int nWidth, const int nHeight)
{
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
JSAMPROW row_pointer[1];
FILE * pJpegFile = NULL;
unsigned char *yuvbuf = NULL;
unsigned char *ybase = NULL, *ubase = NULL;
int i=0, j=0;
int idx=0;
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_compress(&cinfo);
if ((pJpegFile = fopen(pFileName, "wb")) == NULL)
{
return -1;
}
jpeg_stdio_dest(&cinfo, pJpegFile);
// image width and height, in pixels
cinfo.image_width = nWidth;
cinfo.image_height = nHeight;
cinfo.input_components = 3; // # of color components per pixel
cinfo.in_color_space = JCS_YCbCr; //colorspace of input image
jpeg_set_defaults(&cinfo);
jpeg_set_quality(&cinfo, 85, TRUE );
cinfo.jpeg_color_space = JCS_YCbCr;
cinfo.comp_info[0].h_samp_factor = 2;
cinfo.comp_info[0].v_samp_factor = 2;
jpeg_start_compress(&cinfo, TRUE);
if(!(yuvbuf=(unsigned char *)malloc(nWidth*3))!=NULL)
{
return -1;
}
memset(yuvbuf, 0, nWidth*3);
ybase=pYUVBuffer;
ubase=pYUVBuffer+nWidth*nHeight;
while (cinfo.next_scanline < cinfo.image_height)
{
idx=0;
for(i=0;i<nWidth;i++)
{
yuvbuf[idx++]=ybase[i + j * nWidth];
yuvbuf[idx++]=ubase[j/2 * nWidth+(i/2)*2];
yuvbuf[idx++]=ubase[j/2 * nWidth+(i/2)*2+1];
}
row_pointer[0] = yuvbuf;
jpeg_write_scanlines(&cinfo, row_pointer, 1);
j++;
}
free(yuvbuf);
jpeg_finish_compress( &cinfo);
jpeg_destroy_compress(&cinfo);
fclose(pJpegFile);
return 0;
}
int main(int argc, char *argv[]) {
if (argc != 5) {
fprintf(stderr, "Usage: %s <nv12_file> <jpeg_file> <width> <height>\n", argv[0]);
return EXIT_FAILURE;
}
const char *nv12_file = argv[1];
const char *jpeg_file = argv[2];
int width = atoi(argv[3]);
int height = atoi(argv[4]);
// 读取 NV12 数据
size_t nv12_size = width * height * 3 / 2;
unsigned char *nv12_data = (unsigned char *)malloc(nv12_size);
FILE *fp = fopen(nv12_file, "rb");
fread(nv12_data, 1, nv12_size, fp);
fclose(fp);
clipNv12ToJpgFile(jpeg_file, nv12_data, width, height);
free(nv12_data);
return EXIT_SUCCESS;
}
2 Makefile
CROSS_COMPILE:=mips-linux-uclibc-
TOPDIR ?= ./
CC = $(CROSS_COMPILE)gcc
CPP = $(CROSS_COMPILE)g++
STRIP = $(CROSS_COMPILE)strip
CXXFLAGS := -std=c++11 -mfp64 -mnan=2008 -mabs=2008 -Wall -EL -O3 -march=mips32r2 -flax-vector-conversions -lpthread -lrt -ldl -lm
INCLUDES := -I$(TOPDIR)/include
INCLUDES += -I$(TOPDIR)/libjpeg/inc
LIBS := -L$(TOPDIR)/libjpeg/ -ljpeg
TARGET = nv12_to_jpeg
OBJS := main.o
%.o:%.cpp
$(CPP) $(INCLUDES) $(CXXFLAGS) -o $@ -c $^
$(TARGET):$(OBJS)
$(CPP) $(CXXFLAGS) $(OBJS) -o $@ $(INCLUDES) $(LIBS)
all:$(TARGET)
.PHONY: clean
clean:
rm -f $(TARGET) $(OBJS)