上一篇文章是使用libjpeg库进行jpeg图片的解码,现在进行jpeg图片的编码(压缩)。步骤都是一样的,创建编码器,设置源像素数据的格式,设置输出文件句柄,设置输出图片的质量0到100,然后进行编码即可。测试源代码如下:
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include time.h>
- #include
- #include
- #include
- #include
- #include "jpeglib.h"
- #include
- #define CLEAR(x) memset (&(x), 0, sizeof (x))
- int main (int argc, char **argv)
- {
- char * filename = "test.jpeg";
- unsigned char* yuvData;
- int quality = 80;
- int image_width = 640;
- int image_height = 480;
- int i;
-
- yuvData = malloc(640 * 480 * 3);
- for(i=0;i<640 * 480;i++)
- {
- yuvData[i++] = 0xff;
- yuvData[i++] = 0x00;
- yuvData[i] = 0x00;
- }
- for(i;i<640 * 480*2;i++)
- {
- yuvData[i++] = 0x00;
- yuvData[i++] = 0xff;
- yuvData[i] = 0x00;
- }
- for(i;i<640 * 480*3;i++)
- {
- yuvData[i++] = 0x00;
- yuvData[i++] = 0x00;
- yuvData[i] = 0xff;
- }
- yuvData[0] = yuvData[1] = yuvData[2] = 0;
- printf("LINE:%d,%drn",__LINE__,yuvData);
-
- struct jpeg_compress_struct cinfo;
- struct jpeg_error_mgr jerr;
- FILE * outfile; // target file
- JSAMPROW row_pointer[1]; // pointer to JSAMPLE row[s]
- int row_stride; // physical row width in image buffer
- JSAMPIMAGE buffer;
- unsigned char *pSrc,*pDst;
- int band,buf_width[3],buf_height[3];
- cinfo.err = jpeg_std_error(&jerr);
- printf("LINE:%drn",__LINE__);
- jpeg_create_compress(&cinfo);
- printf("LINE:%drn",__LINE__);
- if ((outfile = fopen(filename, "wb")) == NULL) {
- fprintf(stderr, "can't open %sn", filename);
- exit(1);
- }
- jpeg_stdio_dest(&cinfo, outfile);
- printf("LINE:%drn",__LINE__);
- cinfo.image_width = image_width; // image width and height, in pixels
- cinfo.image_height = image_height;
- cinfo.input_components = 3; // # of color components per pixel
- cinfo.in_color_space = JCS_RGB; //colorspace of input image
- jpeg_set_defaults(&cinfo);
- jpeg_set_quality(&cinfo, quality, TRUE );
- ////////////////////////////
- // cinfo.raw_data_in = 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);
- printf("LINE:%drn",__LINE__);
-
-
- while (cinfo.next_scanline < cinfo.image_height)
- {
- row_pointer[0] = &yuvData[cinfo.next_scanline * cinfo.image_width * cinfo.input_components];
- // printf("LINE:%d,%drn",__LINE__,cinfo.next_scanline);
- jpeg_write_scanlines(&cinfo, row_pointer, 1);
- }
- jpeg_finish_compress(&cinfo);
- fclose(outfile);
- jpeg_destroy_compress(&cinfo);
- return 0;
- }
复制代码
压缩得到的jpeg文件在windows或者linux桌面系统下打开即可,正常的话应该是三个长方形彩条。如下图:
|