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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM