Gif(GraphicsInterchange Format,图形交换格式)是由CompuServe公司在1987年开发的图像文件格式,分为87a和89a两种版本。Gif是基于LZW算法的无损压缩算法。Gif图像是基于颜色表的,最多只支持8位(256色)。Gif减少了图像调色板中的色彩数量,从而在存储时达到减少图像文件大小的目的。Gif分为静态Gif和动画Gif两种,扩展名为.gif,是一种压缩位图格式,支持透明背景图像,适用于多种操作系统。
下面利用CxImage开源库,实现对Gif图像进行编解码,主要包括3个文件:
1. funset.h :
#ifndef _FUNSET_H_ #define _FUNSET_H_ #include <string> using namespace std; void decoding_gif(string strGifName, string strSavePath); void encoding_gif(string strImgPath, string strGifName); #endif //_FUNSET_H_
#include "stdafx.h" #include "funset.h" #include <iostream> #include "../CxImage/ximagif.h" #include <io.h> using namespace std; void decoding_gif(string strGifName, string strSavePath) { CxImage img; img.Load(strGifName.c_str(), CXIMAGE_FORMAT_GIF); int iNumFrames = img.GetNumFrames(); cout<<"frames num = "<<iNumFrames<<endl; CxImage* newImage = new CxImage(); for (int i = 0; i < iNumFrames; i++) { newImage->SetFrame(i); newImage->Load(strGifName.c_str(), CXIMAGE_FORMAT_GIF); char tmp[64]; sprintf(tmp, "%d", i); string tmp1; tmp1 = tmp1.insert(0, tmp); tmp1 = strSavePath + tmp1 + ".png"; newImage->Save(tmp1.c_str(), CXIMAGE_FORMAT_PNG); } if (newImage) delete newImage; } int TraverseFolder(const string strFilePath, string strImageNameSets[]) { int iImageCount=0; _finddata_t fileInfo; long handle = _findfirst(strFilePath.c_str(), &fileInfo); if (handle == -1L) { cerr << "failed to transfer files" << endl; return -1; } do { //cout << fileInfo.name <<endl; strImageNameSets[iImageCount] = (string)fileInfo.name; iImageCount ++; } while (_findnext(handle, &fileInfo) == 0); return iImageCount; } void encoding_gif(string strImgPath, string strGifName) { string strImgSets[100] = {}; int iImgCount = TraverseFolder(strImgPath, strImgSets); string strTmp = strImgPath.substr(0, strImgPath.find_last_of("/") +1); CxImage** img = new CxImage*[iImgCount]; if (img == NULL) { cout<<"new Cximage error!"<<endl; return; } for (int i = 0; i < iImgCount; i++) { string tmp1; tmp1 = strTmp + strImgSets[i]; img[i] = new CxImage; img[i]->Load(tmp1.c_str(), CXIMAGE_FORMAT_PNG); } CxIOFile hFile; hFile.Open(strGifName.c_str(), "wb"); CxImageGIF multiimage; multiimage.SetLoops(3); multiimage.SetDisposalMethod(2); multiimage.Encode(&hFile, img, iImgCount, false, false); hFile.Close(); delete [] img; }3. main.cpp:
#include "stdafx.h" #include <iostream> #include "funset.h" using namespace std; int main(int argc, char* argv[]) { string strGifName = "../../Data/fire.gif"; string strSavaPath = "../../Data/"; decoding_gif(strGifName, strSavaPath); string strImgPath = "../../Data/*.png"; strGifName = "../../Data/tmp.gif"; encoding_gif(strImgPath, strGifName); cout<<"ok!!!"<<endl; return 0; }