将图片写入二进制文件,再从二进制文件还原图片(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 }

猜你喜欢

转载自www.cnblogs.com/lyj-blogs/p/10178384.html