LZW编码原理
LZW的编码思想是不断地从字符流中提取新的字符串,通俗地理解为新“词条”,然后用“代号”也就是码字表示这个“词条”。这样一来,对字符流的编码就变成了用码字去替换字符流,生成码字流,从而达到压缩数据的目的。LZW编码是围绕称为词典的转换表来完成的。LZW编码器通过管理这个词典完成输入与输出之间的转换。LZW编码器的输入是字符流,字符流可以是用8位ASCII字符组成的字符串,而输出是用n位(本实验中默认为16位)表示的码字流。
LZW编码算法的步骤如下:
步骤1:将词典初始化为包含所有可能的单字符,当前前缀P初始化为空。
步骤2:当前字符C=字符流中的下一个字符。
步骤3:判断P+C是否在词典中
(1)如果“是”,则用C扩展P,即让P=P+C,返回到步骤2。
(2)如果“否”,则
输出与当前前缀P相对应的码字W;
将P+C添加到词典中;
令P=C,并返回到步骤2
对应代码:
void LZWEncode( FILE *fp, BITFILE *bf){
int character;
int string_code;
int index;
unsigned long file_length;
fseek( fp, 0, SEEK_END);
file_length = ftell( fp);
fseek( fp, 0, SEEK_SET);
BitsOutput( bf, file_length, 4*8);
InitDictionary();
string_code = -1;
while( EOF!=(character=fgetc( fp))){
index = InDictionary( character, string_code);
if( 0<=index){ // string+character in dictionary
string_code = index;
}else{ // string+character not in dictionary
output( bf, string_code);
if( MAX_CODE > next_code){ // free space in dictionary
// add string+character to dictionary
AddToDictionary( character, string_code);
}
string_code = character;
}
}
output( bf, string_code);
}
LZW解码原理
当前位置的码字对应的词为文件内容,加上下一位置的码字的第一个字为新的写入词典的词。连续两次需要向词典写入新词时第二次的词为上一个写入的词加上该词的第一个字。
对应代码:
void LZWDecode( BITFILE *bf, FILE *fp){
int character;
int new_code, last_code;
int phrase_length;
unsigned long file_length;
file_length = BitsInput( bf, 4*8);
if( -1 == file_length) file_length = 0;
/*需填充*/
InitDictionary();
last_code = -1;
while (0 < file_length) {
new_code = input(bf);
if (new_code >= next_code) { //码字对应的字符串还未收录在词典中
d_stack[0] = character;
phrase_length = DecodeString(1, last_code);//d_stack中存入上一个码字所指字符串和上一个码字所指字符串的首字符
}
else {
phrase_length = DecodeString(0, new_code);//d_stack中存入码字所指字符串
}
character = d_stack[phrase_length - 1];//记录码字所指字符串
while (0 < phrase_length) {
phrase_length--;
fputc(d_stack[phrase_length], fp);//将d_stack中所存字符串写入输出文件中
file_length--;
}
if (MAX_CODE > next_code) {
AddToDictionary(character, last_code);//把新字符串存入词典中
}
last_code = new_code;//移动到下一个码字
}
}
当前码字在词典中不存在时:
根据编码时对应情景可知,上一个字符串存入词典后马上遇到了该字符串,所以上一个码字对应的字符串与本码字对应的字符串除去最后一个字符后一致,而最后一个字符与本码字对应字符串的第一个字符相同,由此可解出。
LZW编码效果测试
对11种不同格式文件进行LZW编码压缩
文件类型 | 原文件大小 | LZW压缩后大小 |
---|---|---|
txt | 18B | 28B(变大) |
txtx(内容较重复的文档) | 338,713KB | 118,560KB(压缩) |
xlsx | 18KB | 27KB(变大) |
rar | 20,480KB | 25,154KB(变大) |
ppt | 6,301KB | 5,878KB()压缩) |
207KB | 266KB(变大) | |
mp3 | 5,104KB | 6,223KB(变大) |
mp4 | 470,998KB | 885,591KB(变大) |
jpg | 4,122KB | 4,920KB(变大) |
docx | 18KB | 27KB(变大) |
yuv(bmp图像生成的yuv视频,有多个相同帧与近似画面) | 262,440KB | 690KB(压缩) |
由统计结果与压缩原理可知,LZW在压缩小型文档时,因为词典采用16位表示一个码字,导致未出现重复内容时单个字母占用的空间为编码前的两倍,且因为字符少导致重复度较低,效果较差,最差情况下编码后的大小为原文件大小的两倍;在压缩内容重复度较高的内容如大型文档和较重复的视频时压缩效果较好,越重复效果越明显;英文相对于中文更容易压缩。
词典中每个表示两个字节的码字第一次出现时编码后的文件会相对于原文件变大,每个表示三个字节的码字第一次出现时编码后的文件相对于原文件没有变化,每个表示三个以上字节的码字第一次出现时编码后的文件相对于原文件压缩;词典空间用完后每使用一次表示两个字节的码字则编码后的文件相对于原文件没有变化,每使用一次表示三个及以上字节的码字则编码后的文件相对于原文件压缩。
将词典所用位数调低对于小型文件来说可以使压缩率更高,如使用12位表示一个码字。但对于大型文件来说调低位数会使词典空间变小,有可能使压缩率降低。
所用代码:
bitio.h
/*
* Declaration for bitwise IO
*
* vim: ts=4 sw=4 cindent
*/
#ifndef __BITIO__
#define __BITIO__
#include <stdio.h>
typedef struct{
FILE *fp;
unsigned char mask;
int rack;
}BITFILE;
BITFILE *OpenBitFileInput( char *filename);
BITFILE *OpenBitFileOutput( char *filename);
void CloseBitFileInput( BITFILE *bf);
void CloseBitFileOutput( BITFILE *bf);
int BitInput( BITFILE *bf);
unsigned long BitsInput( BITFILE *bf, int count);
void BitOutput( BITFILE *bf, int bit);
void BitsOutput( BITFILE *bf, unsigned long code, int count);
#endif // __BITIO__
bitio.c
/*
* Definitions for bitwise IO
*
* vim: ts=4 sw=4 cindent
*/
#include <stdlib.h>
#include <stdio.h>
#include "bitio.h"
#define _CRT_SECURE_NO_WARNINGS
BITFILE *OpenBitFileInput( char *filename){
BITFILE *bf;
bf = (BITFILE *)malloc( sizeof(BITFILE));
if( NULL == bf) return NULL;
if( NULL == filename) bf->fp = stdin;
else bf->fp = fopen( filename, "rb");
if( NULL == bf->fp) return NULL;
bf->mask = 0x80;
bf->rack = 0;
return bf;
}
BITFILE *OpenBitFileOutput( char *filename){
BITFILE *bf;
bf = (BITFILE *)malloc( sizeof(BITFILE));
if( NULL == bf) return NULL;
if( NULL == filename) bf->fp = stdout;
else bf->fp = fopen( filename, "wb");
if( NULL == bf->fp) return NULL;
bf->mask = 0x80;
bf->rack = 0;
return bf;
}
void CloseBitFileInput( BITFILE *bf){
fclose( bf->fp);
free( bf);
}
void CloseBitFileOutput( BITFILE *bf){
// Output the remaining bits
if( 0x80 != bf->mask) fputc( bf->rack, bf->fp);
fclose( bf->fp);
free( bf);
}
int BitInput( BITFILE *bf){
int value;
if( 0x80 == bf->mask){
bf->rack = fgetc( bf->fp);
if( EOF == bf->rack){
fprintf(stderr, "Read after the end of file reached\n");
exit( -1);
}
}
value = bf->mask & bf->rack;
bf->mask >>= 1;
if( 0==bf->mask) bf->mask = 0x80;
return( (0==value)?0:1);
}
unsigned long BitsInput( BITFILE *bf, int count){
unsigned long mask;
unsigned long value;
mask = 1L << (count-1);
value = 0L;
while( 0!=mask){
if( 1 == BitInput( bf))
value |= mask;
mask >>= 1;
}
return value;
}
void BitOutput( BITFILE *bf, int bit){
if( 0 != bit) bf->rack |= bf->mask;
bf->mask >>= 1;
if( 0 == bf->mask){ // eight bits in rack
fputc( bf->rack, bf->fp);
bf->rack = 0;
bf->mask = 0x80;
}
}
void BitsOutput( BITFILE *bf, unsigned long code, int count){
unsigned long mask;
mask = 1L << (count-1);
while( 0 != mask){
BitOutput( bf, (int)(0==(code&mask)?0:1));
mask >>= 1;
}
}
#if 0
int main( int argc, char **argv){
BITFILE *bfi, *bfo;
int bit;
int count = 0;
if( 1<argc){
if( NULL==OpenBitFileInput( bfi, argv[1])){
fprintf( stderr, "fail open the file\n");
return -1;
}
}else{
if( NULL==OpenBitFileInput( bfi, NULL)){
fprintf( stderr, "fail open stdin\n");
return -2;
}
}
if( 2<argc){
if( NULL==OpenBitFileOutput( bfo, argv[2])){
fprintf( stderr, "fail open file for output\n");
return -3;
}
}else{
if( NULL==OpenBitFileOutput( bfo, NULL)){
fprintf( stderr, "fail open stdout\n");
return -4;
}
}
while( 1){
bit = BitInput( bfi);
fprintf( stderr, "%d", bit);
count ++;
if( 0==(count&7))fprintf( stderr, " ");
BitOutput( bfo, bit);
}
return 0;
}
#endif
lzw_E.c(在 项目–》属性–》配置属性–》调试–》命令参数中第一个参数输入E为编码,输入D为解码;第二个参数填写输入文件名,第三个参数填写输出文件名)
/*
* Definition for LZW coding
*
* vim: ts=4 sw=4 cindent nowrap
*/
#include <stdlib.h>
#include <stdio.h>
#include "bitio.h"
#define MAX_CODE 65535
struct {
int suffix;
int parent, firstchild, nextsibling;
} dictionary[MAX_CODE+1];
int next_code;
int d_stack[MAX_CODE]; // stack for decoding a phrase
#define input(f) ((int)BitsInput( f, 16))
#define output(f, x) BitsOutput( f, (unsigned long)(x), 16)
int DecodeString( int start, int code);
void InitDictionary( void);
void PrintDictionary( void){
int n;
int count;
for( n=256; n<next_code; n++){
count = DecodeString( 0, n);
printf( "%4d->", n);
while( 0<count--) printf("%x ", (int)(d_stack[count]));
printf( "\n");
}
}
int DecodeString( int start, int code){
int count;
count = start;
while( 0<=code){
d_stack[ count] = dictionary[code].suffix;
code = dictionary[code].parent;
count ++;
}
return count;
}
void InitDictionary( void){
int i;
for( i=0; i<256; i++){
dictionary[i].suffix = i;
dictionary[i].parent = -1;
dictionary[i].firstchild = -1;
dictionary[i].nextsibling = i+1;
}
dictionary[255].nextsibling = -1;
next_code = 256;
}
/*
* Input: string represented by string_code in dictionary,
* Output: the index of character+string in the dictionary
* index = -1 if not found
*/
int InDictionary( int character, int string_code){
int sibling;
if( 0>string_code) return character;
sibling = dictionary[string_code].firstchild;
while( -1<sibling){
if( character == dictionary[sibling].suffix) return sibling;
sibling = dictionary[sibling].nextsibling;
}
return -1;
}
void AddToDictionary( int character, int string_code){
int firstsibling, nextsibling;
if( 0>string_code) return;
dictionary[next_code].suffix = character;
dictionary[next_code].parent = string_code;
dictionary[next_code].nextsibling = -1;
dictionary[next_code].firstchild = -1;
firstsibling = dictionary[string_code].firstchild;
if( -1<firstsibling){ // the parent has child
nextsibling = firstsibling;
while( -1<dictionary[nextsibling].nextsibling )
nextsibling = dictionary[nextsibling].nextsibling;
dictionary[nextsibling].nextsibling = next_code;
}else{// no child before, modify it to be the first
dictionary[string_code].firstchild = next_code;
}
next_code ++;
}
void LZWEncode( FILE *fp, BITFILE *bf){
int character;
int string_code;
int index;
unsigned long file_length;
fseek( fp, 0, SEEK_END);
file_length = ftell( fp);
fseek( fp, 0, SEEK_SET);
BitsOutput( bf, file_length, 4*8);
InitDictionary();
string_code = -1;
while( EOF!=(character=fgetc( fp))){
index = InDictionary( character, string_code);
if( 0<=index){ // string+character in dictionary
string_code = index;
}else{ // string+character not in dictionary
output( bf, string_code);
if( MAX_CODE > next_code){ // free space in dictionary
// add string+character to dictionary
AddToDictionary( character, string_code);
}
string_code = character;
}
}
output( bf, string_code);
}
void LZWDecode( BITFILE *bf, FILE *fp){
int character;
int new_code, last_code;
int phrase_length;
unsigned long file_length;
file_length = BitsInput( bf, 4*8);
if( -1 == file_length) file_length = 0;
/*需填充*/
InitDictionary();
last_code = -1;
while (0 < file_length) {
new_code = input(bf);
if (new_code >= next_code) { //码字对应的字符串还未收录在词典中
d_stack[0] = character;
phrase_length = DecodeString(1, last_code);//d_stack中存入上一个码字所指字符串和上一个码字所指字符串的首字符
}
else {
phrase_length = DecodeString(0, new_code);//d_stack中存入码字所指字符串
}
character = d_stack[phrase_length - 1];//记录码字所指字符串
while (0 < phrase_length) {
phrase_length--;
fputc(d_stack[phrase_length], fp);//将d_stack中所存字符串写入输出文件中
file_length--;
}
if (MAX_CODE > next_code) {
AddToDictionary(character, last_code);//把新字符串存入词典中
}
last_code = new_code;//移动到下一个码字
}
}
int main( int argc, char **argv){
FILE *fp;
BITFILE *bf;
if( 4>argc){
fprintf( stdout, "usage: \n%s <o> <ifile> <ofile>\n", argv[0]);
fprintf( stdout, "\t<o>: E or D reffers encode or decode\n");
fprintf( stdout, "\t<ifile>: input file name\n");
fprintf( stdout, "\t<ofile>: output file name\n");
return -1;
}
if( 'E' == argv[1][0]){ // do encoding
fp = fopen( argv[2], "rb");
bf = OpenBitFileOutput( argv[3]);
if( NULL!=fp && NULL!=bf){
LZWEncode( fp, bf);
fclose( fp);
CloseBitFileOutput( bf);
fprintf( stdout, "encoding done\n");
}
}else if( 'D' == argv[1][0]){ // do decoding
bf = OpenBitFileInput( argv[2]);
fp = fopen( argv[3], "wb");
if( NULL!=fp && NULL!=bf){
LZWDecode( bf, fp);
fclose( fp);
CloseBitFileInput( bf);
fprintf( stdout, "decoding done\n");
}
}else{ // otherwise
fprintf( stderr, "not supported operation\n");
}
PrintDictionary();
return 0;
}