C++读写图片文件

2021/11/30 14:07:18

本文主要是介绍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();            

 



这篇关于C++读写图片文件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程