【原创】用游程编码实现黑白图像的压缩/解压缩

用游程编码方式实现文件的压缩具有很大的局限性,对于类似于黑白图像这样的具有连续相同的大面积颜色块的文件有很
 
高的效率,但是对于彩色图像或其他相邻两点的值都不同的文件来说,反而会增大数据量
 
 
 
#include <iostream>
#include <fstream>
 
using namespace std;
 
struct SP
      {
             int length;
             char ch;
      };
 
int convert(const char* fsource,const char* fdest)  //压缩 
{
    SP sp;
    int Count=1;
        ifstream in(fsource,ios::in|ios::binary);  //以二进制方式读取 
        if(!in) return 0;
        ofstream out(fDest,ios::out|ios::binary); //以二进制方式写入
        if(!out) return 0;
        char ch,p;
        in.read((char*)&ch,sizeof(char));  //读取一个字符,并向后偏移一个字节 
        p=ch;
        do
        {     //需要在read后加一个是否到文件末尾的判断语句,否则会多写入一个结束字符
             in.read((char*)&ch,sizeof(char));
             if(p!=ch || in.eof())  //如果当前字符和前一个字符不同或到了文件末尾
             {
                  sp.ch=p;
                  sp.length=Count;  //该字符的数量
                  out.write((char*)&sp,sizeof(sp));   //写入一个SP类型的结构
                  Count=1;
             }
             else  
                   Count++; 
             p=ch;
        }while(!in.eof());
        out.close();
        in.close(); 
        return 1;      
}
 
int reconvert(const char* fsource,const char* fdest)  //解压 
{
       SP sp;
 
       ifstream in(fsource,ios::in|ios::binary); //以二进制读取方式打开压缩后的文件
       if(!in) return 0;
       ofstream out(fdest,ios::out|ios::binary); //以二进制写入方式打开一个文件
       if(!out) return 0;
       do
       {         //需要在read后加一个是否到文件末尾的判断语句,否则会多写入一个结束字符
                in.read((char*)&sp,sizeof(sp));
                if(in.eof()) break;     
                for(int i=0;i<(int)sp.length;i++)
                    out.write((char*)&sp.ch,sizeof(char));
       }while(!in.eof()); 
       out.close();
       in.close();
       return 1;                
}
 
int main(int argc,char* argv[])
{
         convert("test.bmp","test.rlc");
         reconvert("test.rlc","dest.bmp");
         return 0;
}

posted @ 2009-11-17 15:43  leukotrichia  阅读(1631)  评论(2编辑  收藏  举报