读取图片文件,读到内存后,再访问内存数据,另存为图片文件,亲测有效!
代码:
#include <fstream> using namespace std; void main() { //一、打开jpg文件 // 1. 打开图片文件 ifstream is("D:\\test.jpg", ifstream::in | ios::binary); // 2. 计算图片长度 is.seekg(0, is.end); int length = is.tellg(); cout << length <<endl; is.seekg(0, is.beg); // 3. 创建内存缓存区 char * buffer = new char[length]; // 4. 读取图片 is.read(buffer, length); // 到此,图片已经成功的被读取到内存(buffer)中 //二、另存为 223.jpg std::string strFile ; for (size_t i = 0; i < length; i++) { strFile += buffer[i]; } //1.打开保存文件,没有自动创建 ofstream fout("D:\\23.jpg" , ios::binary); if (!fout) return ; if (!fout) { cout << "文件不能打开" << endl; } else { //2.输出到磁盘文件 cout << "文件大小:" << strFile.size()<< endl; fout.write(strFile.c_str(), strFile.size()); fout.close(); } delete[] buffer; buffe =NULL; }测试结果:对比文件大小,大小一致,另存为的图片文件打开正确
注意:图片路径为绝对路径
资料参考:
http://www.cplusplus.com/reference/istream/istream/read/
https://blog.csdn.net/qq_29695701/article/details/84262492?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~all~top_click~default-2-84262492.nonecase&utm_term=%E6%89%93%E5%BC%80%E5%9B%BE%E7%89%87&spm=1000.2123.3001.4430
