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();            

 

posted @ 2021-11-30 12:53  钟齐峰  阅读(1143)  评论(0编辑  收藏  举报