LZW算法又叫“串表压缩算法”就是通过建立一个字符串表,用较短的代码来表示较长的字符串来实现压缩。
1.基本原理
提取原始文本文件数据中的不同字符,基于这些字符创建一个编译表,然后用编译表中的字符的索引来替代原始文本文件数据中的相应字符,减少原始数据大小。看起来和调色板图象的实现原理差不多,但是应该注意到的是,我们这里的编译表不是事先创建好的,而是根据原始文件数据动态创建的,解码时还要从已编码的数据中还原出原来的编译表。
下面我们来一一解析LZW的编码与解码:
(1)编码
LZW编码的核心思想是从输入数据中创建一个“字典”,把任意字符的组合收录于字典中。编码数据过程中当遇到已经在字典中出现的“短语”时,编码器就输出该词条的“索引号”,而不是短语本身,以实现压缩。
具体实现步骤如下:
下面我们通过一个例子来分析:
对如下字符串“abbababac”进行LZW编码
“abbababac”最后编码为“97 98 98 256 259 99”
输入:8bit × 9 = 72bit
输出:9bit × 6 = 54bit
(2)解码
编码过程中建立的词典,实际上并不与码流一起传送。这主要考虑到以下两点:
- 由于码表可能占用的空间很大,不传送码表可以将压缩比最大化
- 如果需要等收到编码端的词典后再进行解码,便不可能实现编解码两端的同步操作
那么,我们就要在解码端按照与编码端相同的规则同步地建立词典。
具体实现步骤如下:
下面我们仍然以上述例子来分析:
“abbababac”编码为“97 98 98 256 259 99”,对“97 98 98 256 259 99”进行解码
“97 98 98 256 259 99”最后编码为“abbababac”
2.代码实现
bitio.h:
#pragma once
/*
* 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__
Lzw_E.cpp:
/*
* Definition for LZW coding
*
* vim: ts=4 sw=4 cindent nowrap
*/
#include <cstdio>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <cstdio>
#include "bitio.h"
#define MAX_CODE 65535
using namespace std;
struct {
int suffix = -1;//后缀
int parent = -1, firstchild = -1, nextsibling = -1;//父亲,孩子,兄弟姐妹
} 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 PrintDictionary(void) {
int n;
int count;
for (n = 256; n < next_code; n++) {
count = DecodeString(0, n);
printf("%4d->", n);
while (0 < count--) printf("%c", (char)(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;
}
int SearchChar(int new_code, int& character)
{
int code = new_code;
int count = 0;
while (0 <= code) {
character = dictionary[code].suffix;
code = dictionary[code].parent;
count++;
}
return count;
}
void PrintCW(int phrase_length, int new_code, FILE* fp)
{
int code = new_code;
int count = phrase_length;
unsigned char* fileout = new unsigned char[phrase_length];
while (0 < count--) {
fileout[count] = unsigned char(dictionary[code].suffix);
code = dictionary[code].parent;
}
for (int i = 0; i < phrase_length; i++)
fprintf(fp, "%c", fileout[i]);
}
//初始化词典
void InitDictionary(void)
{
int i;
/*初始字典中每一个节点的根节点都是自身,兄弟姐妹就是自己+1,
只有第256个没有兄弟姐妹*/
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; //下一个要进行插入的suffix就是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; //前缀为string_code的first_child
while (-1 < sibling) {
if (character == dictionary[sibling].suffix)
return sibling; //如果查到了child的尾缀和character相同,说明string+character在词典中,返回sibling
sibling = dictionary[sibling].nextsibling; //若不相同,则继续找这个child的nextsibling,直到找出or没有nextsibling了
}
return -1;
}
void AddToDictionary(int character, int string_code)
{
int firstsibling, nextsibling;
if (0 > string_code) return;
dictionary[next_code].suffix = character; //尾缀字符添加为character
dictionary[next_code].parent = string_code; //前缀为string_code
dictionary[next_code].nextsibling = -1; //没有nextsibling
dictionary[next_code].firstchild = -1; //没有firstchild
firstsibling = dictionary[string_code].firstchild; //firstsibling是查找string_code得到的firstchild
if (-1 < firstsibling) { // the parent has child
nextsibling = firstsibling;
while (-1 < dictionary[nextsibling].nextsibling)
nextsibling = dictionary[nextsibling].nextsibling;
//如果string_code的树里面已经有后缀了,循环查找nextsibling的下一个值,直至循环到表末尾
dictionary[nextsibling].nextsibling = next_code; //将nextsibling的下一个字符设置为next_code
}
else {// no child before, modify it to be the first
dictionary[string_code].firstchild = next_code; //如果没有后缀,那么将first child设置为next_code
}
next_code++; //next_code+1,等待下一次词典的添加
}
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); //写文件长度(32bits)
InitDictionary(); //初始化字典树
string_code = -1; //表示为空
while (EOF != (character = fgetc(fp)))
{
index = InDictionary(character, string_code); //判断字符是否在字典中
if (0 <= index) { // 若0 <= index,那么将string+character设置为新的string
string_code = index;
}
else { // string+character不在词典中
output(bf, string_code); //输出string_code
if (MAX_CODE > next_code) {
AddToDictionary(character, string_code); //将新字符串输入
}
string_code = character;
}
}
output(bf, string_code);
PrintDictionary();
}
void LZWDecode(BITFILE* bf, FILE* fp) {
int character = -1;
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();
new_code = input(bf);
last_code = new_code;
fprintf(fp, "%c", new_code);
int decode_length = 1;
while (decode_length < file_length) //没读到文件末尾的情况
{
new_code = input(bf);
decode_length++;
if (dictionary[new_code].suffix != -1)//在字典中
{
phrase_length = SearchChar(new_code, character);
PrintCW(phrase_length, new_code, fp);
AddToDictionary(character, last_code);
last_code = new_code;
decode_length = decode_length + phrase_length - 1;
}
else//不在字典中
{
phrase_length = SearchChar(last_code, character);
int temp = next_code;
next_code = new_code;
AddToDictionary(character, last_code);
next_code = temp + 1;
PrintCW(phrase_length + 1, new_code, fp);
last_code = new_code;
decode_length = phrase_length + decode_length;
}
}
PrintDictionary();
}
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]) //如果第一个参数是E,开始编码
{
errno_t err = 0;
err = fopen_s(&fp, argv[2], "rb");
bf = OpenBitFileOutput(argv[3]);
if (err == 0 && NULL != bf) {
LZWEncode(fp, bf);
fclose(fp);
CloseBitFileOutput(bf);
fprintf(stdout, "encoding done\n");
}
}
else if ('D' == argv[1][0]) { //如果第一个参数是D,开始解码
bf = OpenBitFileInput(argv[2]);
errno_t err = 0;
err = fopen_s(&fp, 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");
}
return 0;
}
bitio.cpp:
/*
* Definitions for bitwise IO
*
* vim: ts=4 sw=4 cindent
*/
#include <stdlib.h>
#include <stdio.h>
#include "dasasds.h"
BITFILE* OpenBitFileInput(char* filename) {
BITFILE* bf;
bf = (BITFILE*)malloc(sizeof(BITFILE));
if (NULL == bf) {
return NULL;
}
if (NULL == filename) {
bf->fp = stdin;
}
else {
errno_t err = 0;
err = fopen_s(&(bf->fp), 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 {
errno_t err = 0;
err = fopen_s(&(bf->fp), filename, "wb");
if (err != 0)
return NULL;
}
if (NULL == bf->fp) return NULL;
bf->mask = 0x80;//初始化mask=0x80
bf->rack = 0; //初始化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; //mask = mask/2;
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);//把rack写到fp中
bf->rack = 0; //重新初始化rack = 0
bf->mask = 0x80;//重新初始化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
写一个TXT文件,验证代码是否正确:
编解码后的结果与原内容一样
之后,从电脑中已有的文件中,随机选取了txt、PDF、JPG、BMP、MP3、doc、PNG、xlsx、PPT和tex共十种文件格式的各一份文件,使用LZW编码器进行编码。
可得编解码结果:
计算压缩比:
可知,LZW编码在某些文件格式的压缩上可以起到很好的效果,但对有些文件压缩反而会起到反效果(变大了)。这可能是因为由于文件的编码格式要求限制,一部分文件中字符的重复概率很高,而另一部分文件中字符的重复概率很低,造成了LZW在压缩不同文件时展现出相反的效果。
总体来说,本文的LZW编码方法可以适用于一定范围的文件类型,且可以正确对编码文件进行解码,若要提高其鲁棒性,可以进行进一步优化。