C++: 通过文件流读取图片文件
读取图片文件,读到内存后,再访问内存数据,另存为图片文件,亲测有效!
代码:
#include<iostream>
#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;
buffer = NULL;
}
测试结果:对比文件大小,大小一致,另存为的图片文件打开正确
注意:图片路径为绝对路径
资料参考: