use*_*007 4 c++ ifstream ofstream ppm
尝试以我知道的方式读取和写入PPM图像文件(.ppm):
std::istream& operator >>(std::istream &inputStream, PPMObject &other)
{
inputStream.seekg(0, ios::end);
int size = inputStream.tellg();
inputStream.seekg(0, ios::beg);
other.m_Ptr = new char[size];
while (inputStream >> other.m_Ptr >> other.width >> other.height >> other.maxColVal)
{
other.magicNum = (string) other.m_Ptr;
}
return inputStream;
}
Run Code Online (Sandbox Code Playgroud)
我的值对应于实际文件.所以我乐意尝试写数据:
std::ostream& operator <<(std::ostream &outputStream, const PPMObject &other)
{
outputStream << "P6" << " "
<< other.width << " "
<< other.height << " "
<< other.maxColVal << " "
;
outputStream << other.m_Ptr;
return outputStream;
}
Run Code Online (Sandbox Code Playgroud)
我确保使用std :: ios :: binary打开文件进行读写:
int main ()
{
PPMObject ppmObject = PPMObject();
std::ifstream image;
std::ofstream outFile;
image.open("C:\\Desktop\\PPMImage.ppm", std::ios::binary);
image >> ppmObject;
image.clear();
image.close();
outFile.open("C:\\Desktop\\NewImage.ppm", std::ios::binary);
outFile << ppmObject;
outFile.clear();
outFile.close();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
逻辑错误:
我只写了一部分图像.标题没有问题或手动打开文件.
类公共成员变量:
m_Ptr成员变量是char*,height,width maxColrVal都是整数.
尝试解决方案:
使用inputStream.read和outputStream.write来读取和写入数据,但我不知道我尝试过的方式和方法不起作用.
由于我的char*m_Ptr包含所有像素数据.我可以遍历它:
for (int I = 0; I < other.width * other.height; I++) outputStream << other.m_Ptr[I];
Run Code Online (Sandbox Code Playgroud)
但由于某种原因,这会导致运行时错误.
基于http://fr.wikipedia.org/wiki/Portable_pixmap,P6是二进制图像.这会读取单个图像.请注意,不执行检查.这需要添加.
std::istream& operator >>(std::istream &inputStream, PPMObject &other)
{
inputStream >> other.magicNum;
inputStream >> other.width >> other.height >> other.maxColVal;
inputStream.get(); // skip the trailing white space
size_t size = other.width * other.height * 3;
other.m_Ptr = new char[size];
inputStream.read(other.m_Ptr, size);
return inputStream;
}
Run Code Online (Sandbox Code Playgroud)
此代码写入单个图像.
std::ostream& operator <<(std::ostream &outputStream, const PPMObject &other)
{
outputStream << "P6" << "\n"
<< other.width << " "
<< other.height << "\n"
<< other.maxColVal << "\n"
;
size_t size = other.width * other.height * 3;
outputStream.write(other.m_Ptr, size);
return outputStream;
}
Run Code Online (Sandbox Code Playgroud)
m_Ptr仅包含RGB像素值.
我在网上下载的图像(http://igm.univ-mlv.fr/~incerti/IMAGES/COLOR/Aerial.512.ppm)上测试了代码,并使用了以下结构PPMObject.
struct PPMObject
{
std::string magicNum;
int width, height, maxColVal;
char * m_Ptr;
};
Run Code Online (Sandbox Code Playgroud)