用IJG的jpeglib压缩文件,目标都设成个FILE * outfile;
压缩完了就写到文件里去了,而且只有个压缩质量的参数,不知道根据那个参数压出来的文件尺寸会多大;
我弄个办法解决鸭的,不过比较傻;
这是个基本用法,用这个函数把RGB buffer压缩成个jpeg文件存起来,而我只需要他压缩到一个buffer里给我就行了,我不想要文件存储IO开销;
BOOL RGBToJpegFile(const char * fileName, BYTE *dataBuf, UINT widthPix, UINT height, BOOL color, int quality)
{
if (dataBuf==NULL)
return FALSE;
if (widthPix==0)
return FALSE;
if (height==0)
return FALSE;
LPBYTE tmp;
if (!color) {//处理黑白图像
tmp = (BYTE*)new BYTE[widthPix*height];
if (tmp==NULL) {
return FALSE;
}
UINT row,col;
for (row=0;row for (col=0;col LPBYTE pRed, pGrn, pBlu;
pRed = dataBuf + row * widthPix * 3 + col * 3;
pGrn = dataBuf + row * widthPix * 3 + col * 3 + 1;
pBlu = dataBuf + row * widthPix * 3 + col * 3 + 2;
// luminance
int lum = (int)(.299 * (double)(*pRed) + .587 * (double)(*pGrn) + .114 * (double)(*pBlu));
LPBYTE pGray;
pGray = tmp + row * widthPix + col;
*pGray = (BYTE)lum;
}
}
}
struct jpeg_compress_struct cinfo;
FILE * outfile=NULL; /* 目标文件 */
int row_stride; /* 行宽*/
struct my_error_mgr jerr;
/* Step 1: 分配对象*/
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = my_error_exit;
if (setjmp(jerr.setjmp_buffer)) {
/* 出错了 */
jpeg_destroy_compress(&cinfo);
if (outfile!=NULL)
fclose(outfile);
if (!color) {
delete [] tmp;
}
return FALSE;
}
/* 初始化. */
jpeg_create_compress(&cinfo);
/* Step 2: 指定目标 */
if ((outfile = fopen(fileName, "wb")) == NULL) {
return FALSE;
}
jpeg_stdio_dest(&cinfo, outfile);
/* Step 3: 设参数*/
cinfo.image_width = widthPix; /* 宽度*/
cinfo.image_height = height;/* 高度*/
if (color) {
cinfo.input_components = 3; /* # of color components per pixel */
cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
} else {
cinfo.input_components = 1; /* # of color components per pixel */
cinfo.in_color_space = JCS_GRAYSCALE; /* colorspace of input image */
}
jpeg_set_defaults(&cinfo);
jpeg_set_quality(&cinfo, quality, TRUE ); /*设参数*/
/* Step 4: 开始压缩*/
jpeg_start_compress(&cinfo, TRUE);
/* Step 5: 逐行写入 */
row_stride = widthPix * 3; /* 行宽*/
while (cinfo.next_scanline < cinfo.image_height) {
/* 逐行写入 */
LPBYTE outRow;
if (color) {
outRow = dataBuf + (cinfo.next_scanline * widthPix * 3);
} else {
outRow = tmp + (cinfo.next_scanline * widthPix);
}
(void) jpeg_write_scanlines(&cinfo, &outRow, 1);
}
/* Step 6: 完成压缩*/
jpeg_finish_compress(&cinfo);
/* 关闭文件. */
fclose(outfile);
/* Step 7: 释放对象*/
jpeg_destroy_compress(&cinfo);
if (!color)
delete [] tmp;
/* 完成*/
return TRUE;
}
===========================================================================
解决起来挺傻的,不知道有没有人有更好的办法,反正我是一直没再花心思琢磨它,有个用就好了;
定义了一个这样的结构
typedef struct {
unsigned char * buff;
long buffsize;
long next_byte_to_write;
}XXX_JPEG_FILE_BUFFER;
XXX_JPEG_FILE_BUFFER filebuffer;
jpeg_stdio_destf(&cinfo, &filebuffer); //把结构替代输出文件作为目标设进去就行了;这样压缩完成的图片就在buffer里了
不过jpeg_stdio_destf这个函数是不一样的,我自己对jpeglib做了修改,增加了这么一个函数;具体内容下面详述;
#define JPEG_BUFFERSIZE 0x100000