C++ achieve single picture read and save

  • 2020-06-07 04:59:32
  • OfStack

C++ is used to read and save individual pictures. C language can be referred to and is relatively simple.


#include<iostream>
 
using namespace std;
 
 void main(void)
 {
 // Save the input image file name and the output image file name 
 char InImgName[10];
 char OutImgName[10];
 // Image data length 
 int length;
 // The file pointer 
 FILE* fp;
 // Enter the name of the image to read 
 cout<<"Enter Image name:";
 cin>>InImgName;
 // In order to 2 Base mode opens the image 
 if ( (fp=fopen(InImgName, "rb" ))==NULL )
 {
  cout<<"Open image failed!"<<endl;
  exit(0);
 }
 // Get the total length of image data 
 fseek(fp, 0, SEEK_END);
 length=ftell(fp);
 rewind(fp);
 // Allocate memory according to the length of image data buffer
 char* ImgBuffer=(char*)malloc( length* sizeof(char) );
 // Read in the image data buffer
 fread(ImgBuffer, length, 1, fp);
 fclose(fp);
 // Enter the file name to save 
 cout<<"Enter the name you wanna to save:";
 cin>>OutImgName;
 // In order to 2 Radix write mode 
 if ( (fp=fopen(OutImgName, "wb"))==NULL)
 {
  cout<<"Open File failed!"<<endl;
  exit(0);
 }
 // from buffer Write data to fp Point to a file 
 fwrite(ImgBuffer, length, 1, fp);
 cout<<"Done!"<<endl;
 // Close the file pointer and release buffer memory 
 fclose(fp);
 free(ImgBuffer);
 }

Related articles: