C++实现读取图片长度和宽度
看到一个用ASP写的读取图片文件的长度、宽度的程序,感觉有点意思,于是用C++也写了一个。
#include<iostream> #include<fstream> #include<string> usingnamespacestd; classCImage { private: longm_Width; longm_Height; intget_extension(stringfname); public: CImage() { m_Width=0; m_Height=0; }; voidLoadImage(char*fname); longget_width() { returnm_Width; }; longget_height() { returnm_Height; }; }; intCImage::get_extension(stringfname) { charc=fname.at(fname.length()-1); charc2=fname.at(fname.length()-3); if((c=='f')&&(c2=='g')){//fileextensionnameisgif return1; }elseif((c=='g')&&(c2=='j')){//fileextensionnameisjpg return2; }elseif((c=='g')&&(c2=='p')){//fileextensionnameispng return3; }elseif((c=='p')&&(c2=='b')){//fileextensionnameisbmp return4; } return0; } voidCImage::LoadImage(char*fname) { m_Width=m_Height=0; ifstreamffin(fname,std::ios::binary); if(!ffin){ cout<<"Cannotopenthisfile."<<endl; return; } intresult=get_extension(fname); chars1[2]={0},s2[2]={0}; switch(result) { case1://gif ffin.seekg(6); ffin.read(s1,2); ffin.read(s2,2); m_Width=(unsignedint)(s1[1])<<8|(unsignedint)(s1[0]); m_Height=(unsignedint)(s2[1])<<8|(unsignedint)(s2[0]); break; case2://jpg ffin.seekg(164); ffin.read(s1,2); ffin.read(s2,2); m_Width=(unsignedint)(s1[1])<<8|(unsignedint)(s1[0]); m_Height=(unsignedint)(s2[1])<<8|(unsignedint)(s2[0]); break; case3://png ffin.seekg(17); ffin.read(s1,2); ffin.seekg(2,std::ios::cur); ffin.read(s2,2); m_Width=(unsignedint)(s1[1])<<8|(unsignedint)(s1[0]); m_Height=(unsignedint)(s2[1])<<8|(unsignedint)(s2[0]); break; case4://bmp ffin.seekg(18); ffin.read(s1,2); ffin.seekg(2,std::ios::cur); ffin.read(s2,2); m_Width=(unsignedint)(s1[1])<<8|(unsignedint)(s1[0]); m_Height=(unsignedint)(s2[1])<<8|(unsignedint)(s2[0]); break; default: cout<<"NO"<<endl; break; } ffin.close(); }; intmain(intargc,char*argv[]) { if(argc<2){ printf("usage:programimagefilename/n"); return0; } CImagetest; test.LoadImage(argv[1]); cout<<"width:"<<test.get_width()<<endl; cout<<"height:"<<test.get_height()<<endl; return0; }