Zlib 导出了几个函数能很方便的压缩数据,deflate、deflateInit_、compress、compress比较简单。
deflateInit_ (strm), (level), ZLIB_VERSION, sizeof(z_stream)
ZLIB_VERSION 可以使用 zlibVersion 获得 level(压缩级别) 有 10 个 [-1 / 9] -1默认压缩级别Z_DEFAULT_COMPRESSION,z_stream size 为 0x38
z_stream 结构- typedef struct z_stream_s {
- Bytef *next_in; /* next input byte */
- uInt avail_in; /* number of bytes available at next_in */
- uLong total_in; /* total nb of input bytes read so far */
- Bytef *next_out; /* next output byte should be put there */
- uInt avail_out; /* remaining free space at next_out */
- uLong total_out; /* total nb of bytes output so far */
- char *msg; /* last error message, NULL if no error */
- struct internal_state FAR *state; /* not visible by applications */
- alloc_func zalloc; /* used to allocate the internal state */
- free_func zfree; /* used to free the internal state */
- voidpf opaque; /* private data object passed to zalloc and zfree */
- int data_type; /* best guess about the data type: ascii or binary */
- uLong adler; /* adler32 value of the uncompressed data */
- uLong reserved; /* reserved for future use */
- } z_stream ;
复制代码 该结构为空deflateInit_执行完毕后该结构会被初始化,但是next_in、avail_in、next_out、avail_out结构成员需要手动填充。avail_in代表读入的数据量,next_in指向读入数据的指针,next_out代表数据压缩后的输出指针,avail_out代表数据压缩后的大小。
手动填充完这4个成员后调用deflate压缩数据。
deflate (z_streamp strm, int flush)
第一个参数是z_streamp结构指针,int flush有4个值可选Z_NO_FLUSH、Z_SYNC_FLUSH、Z_FULL_FLUSH、Z_FINISH 。Z_NO_FLUSH会设置该函数在压缩时会积聚多少数据,但是并不会输出压缩后的数据流,Z_SYNC_FLUSH会设置所有的未处理的输出传输到输出缓冲,Z_FULL_FLUSH同Z_SYNC_FLUSH差不多不过会把刷新状态会复位,Z_FINISH则和Z_NO_FLUSH差不多不过会输出被压缩的数据流。该函数会返回三种状态 负数 Error 、 0x0 Z_OK 、0x1 Z_STREAM_END到达文件末尾,可以检测返回值0x1来判断压缩是否结束。
最后记得deflateend |