编码程序
#include <iostream>
#include <string>
#include <algorithm>//排序函数所用
#include "stdio.h"
#include "Hxlbmpfile.h"
using namespace std;
typedef struct Temp_Node
{
unsigned char pixel;//ASCII字符
unsigned long weight;//权重,像素出现的次数
}Temp_Node;
typedef struct Huf_Node
{
unsigned char pixel;//ASCII码对应0-255
unsigned long weight; //该节点的“重量”:像素次数
char *code; //该节点对应的编码
int lchild,rchild,parent; //左右孩子 父节点
Huf_Node() {parent=0;}//设节点的父节点为空
}Huf_Node,*Huf_Tree;
int Getweight(HXLBMPFILE *bmpfile,Temp_Node *tempnodes);//由文件获得像素出现的频率
bool encode(char *bmpfname,char *encodefname); //对于给定的bmp文件进行编码
void InitializeHufNode(Temp_Node *tempnodes,Huf_Node *nodelist,int charkinds);//初始化叶子节点
void select(Huf_Node *huf_tree,int n,int *s);//找出规定范围没有父节点的节点最小值
void CreateHufTree(Huf_Node *nodelist,int charkinds,int nodenum); //建立赫夫曼二叉树
void CtreateHufcode(Huf_Node *nodelist,int charkinds);//对叶子结点进行编码
void Save_Encodefile(HXLBMPFILE *bmpfile,char *encodefname,int charkinds,Huf_Node *nodelist);//保存编码文件
bool encode(char *bmpfname,char *encodefname);//进行编码
bool cmp2(Temp_Node a,Temp_Node b) //比较两个list元素的大小
{
return a.weight>b.weight;
}
int Getweight(HXLBMPFILE *bmpfile,Temp_Node *tempnodes)
{
int i,j;
int nodenum=0;
for(i=0;i<256;i++)
{
(tempnodes+i)->weight=0;
(tempnodes+i)->pixel=(unsigned char)i;
//cout<<(int)(tempnodes+i)->pixel<<"\t"<<(tempnodes+i)->weight<<endl;
}
for(i=0;i<bmpfile->imageh;i++)//获取总像素的
{
for(j=0;j<bmpfile->imagew;j++)
{
(tempnodes+bmpfile->pDataAt(i)[j])->weight+=1;
}
}
sort(tempnodes,tempnodes+256,cmp2);
for(i=0;i<256;i++)//共有多少个像素出现过
{
//cout<<(int)(tempnodes+i)->pixel<<"\t"<<(tempnodes+i)->weight<<endl;
if((tempnodes+i)->weight>0&&(tempnodes+i+1)->weight==0)
nodenum=i+1;
}
return nodenum;
}
void InitializeHufNode(Temp_Node *tempnodes,Huf_Node *nodelist,int charkinds)//初始化叶子节点
{
int i=0;
for(i=0;i<charkinds;i++)
{
(nodelist+i)->weight=(tempnodes+i)->weight;
(nodelist+i)->pixel=(tempnodes+i)->pixel;
(nodelist+i)->lchild=-1;
(nodelist+i)->rchild=NULL;
}
}
void select(Huf_Node *huf_tree,int n,int *s)//找出规定范围没有父节点的节点最小值
{
unsigned long m=ULONG_MAX;//无符号长整数最大值
for(int i=0;i<n;i++)
{
if(!huf_tree[i].parent&&huf_tree[i].weight<m)
{
m=huf_tree[i].weight;
*s=i;
}
}
huf_tree[*s].parent=1;
}
void CreateHufTree(Huf_Node *nodelist,int charkinds,int nodenum) //建立二叉树
{
int i;
int s1=0,s2=0;
for(i=charkinds;i<noden