C++读写图片文件

1、C方式

    string sourcefilename = "D:\\Logo.jpg";
    string destfilename="D:\\Logo1.jpg";
    
    FILE* fp; 
    if ( (fp=fopen(sourcefilename.c_str(), "rb" ))==NULL )
    {    
        return;        
    }
 
    fseek(fp, 0, SEEK_END);
    int length=ftell(fp);
    rewind(fp);
    char* ImgBuffer=(char*)malloc( length* sizeof(char) );

    fread(ImgBuffer, length, 1, fp);
    fclose(fp);
    if ( (fp=fopen(destfilename.c_str(), "wb"))==NULL)
    {    
         return;
    }
    fwrite(ImgBuffer,sizeof(char) *iSize, 1, fp);
    fclose(fp);
    free(ImgBuffer);

2、STL方式

    #include<fstream>
    #include <iostream>

    string sourcefilename = "D:\\Logo.jpg";
    string destfilename="D:\\Logo1.jpg";

    std::ifstream fin(sourcefilename.c_str(), std::ios::binary);
    fin.seekg(0, ios::end);
    int iSize = fin.tellg();
    char* ImgBuffer = new char[ sizeof(char) *iSize];
    fin.seekg(0, ios::beg);
    fin.read(ImgBuffer, sizeof(char) * iSize);
    fin.close();

    std::ofstream outFile(destfilename.c_str(), ios::out | ios::binary);    
    outFile.write(ImgBuffer,sizeof(char) * iSize);
    outFile.close();            

 

上一篇:【React工作记录三】React中如何跳转页面传参(参数较短)


下一篇:python笔记71 - traceback.print_exc()保存异常内容