1. 程式人生 > >將圖片寫入二進位制檔案,再從二進位制檔案還原圖片(c++)

將圖片寫入二進位制檔案,再從二進位制檔案還原圖片(c++)

 1 #include "string"
 2 #include "iostream"
 3 #include "fstream"
 4 using namespace std;
 5 #define MAX 20480
 6 void main()
 7 {
 8     string sPicPath = "E:\\10kb.jpg"; 
 9     string sSavePath = "E:\\Binary.bat";
10     string sGetPic = "E:\\newpicture.png";
11     ifstream fin(sPicPath.c_str(), ios::binary);
12 if(!fin) 13 { 14 cout<<"can't open "<<sPicPath<<endl; 15 return; 16 } 17 fin.seekg(0,ios::end);//reset FilePtr Position as the end 18 int ByteLen = fin.tellg();//get file length(bytes) 19 cout<<"the file length : "<<ByteLen<<" Bytes"<<endl;
20 fin.seekg(0,ios::beg);//restore saved pos 21 char pBuffer[MAX] = {0}; 22 fin.read(pBuffer, sizeof(pBuffer)); 23 fin.close(); 24 ofstream fout(sSavePath.c_str(), ios::binary); 25 if(!fout) 26 return; 27 fout.write(pBuffer,sizeof(pBuffer)); 28 fout.close(); 29 ifstream fins(sSavePath.c_str(), ios::binary);
30 if(!fins) 31 { 32 cout<<"can't open "<<sSavePath<<endl; 33 return; 34 } 35 memset(pBuffer,0,sizeof(pBuffer)); 36 fins.read(pBuffer, sizeof(pBuffer)); 37 fins.close(); 38 ofstream fouts(sGetPic.c_str(), ios::binary); 39 if(!fouts) 40 return; 41 fouts.write(pBuffer, sizeof(pBuffer)); 42 cout<<"new file path: "<<sGetPic<<endl; 43 fouts.close(); 44 }