jpg压缩原理可以参考这篇文章,我很早以前转的一篇文章。
没有使用libjpeg的压缩代码可以看看这篇文章,也是我很早以前转的。
这次使用libjpeg库压缩和的解压正好对应起来,有好多函数名称我都是对称的起的,所以结合起来看效果更好。
和上一篇一样,只能处理24位和8位的图像。
代码如下:
#include#include extern "C"{#include "jpeglib.h"};#pragma comment(lib,"jpeg.lib")using namespace std;#pragma pack(2) //两字节对齐,否则bmp_fileheader会占16Bytestruct bmp_fileheader{ unsigned short bfType; //若不对齐,这个会占4Byte unsigned long bfSize; unsigned short bfReverved1; unsigned short bfReverved2; unsigned long bfOffBits;};struct bmp_infoheader{ unsigned long biSize; unsigned long biWidth; unsigned long biHeight; unsigned short biPlanes; unsigned short biBitCount; unsigned long biCompression; unsigned long biSizeImage; unsigned long biXPelsPerMeter; unsigned long biYpelsPerMeter; unsigned long biClrUsed; unsigned long biClrImportant;};FILE *input_file;FILE *output_file;struct bmp_fileheader bfh;struct bmp_infoheader bih;unsigned char *src_buffer;unsigned char *dst_buffer;void read_bmp_header(){ fread(&bfh,sizeof(struct bmp_fileheader),1,input_file); fread(&bih,sizeof(struct bmp_infoheader),1,input_file);}void read_bmp_data(){ fseek(input_file,bfh.bfOffBits,SEEK_SET); src_buffer=new unsigned char[bih.biWidth*bih.biHeight*bih.biBitCount/8]; fread(src_buffer,sizeof(unsigned char)*bih.biWidth*bih.biHeight*bih.biBitCount/8,1,input_file); unsigned long width=bih.biWidth; unsigned long height=bih.biHeight; unsigned short depth=unsigned short(bih.biBitCount/8); unsigned char *src_point; unsigned char *dst_point; dst_buffer=new unsigned char[width*height*depth]; src_point=src_buffer+width*depth*(height-1); dst_point=dst_buffer+width*depth*(height-1); for (unsigned long i=0;i alloc_sarray) ((j_common_ptr)&cinfo,JPOOL_IMAGE,width*depth,1); point=dst_buffer+width*depth*(height-1); while (cinfo.next_scanline