C++ 读取/写入PPM图像文件C++;
尝试以我知道的唯一方式读取/写入PPM图像文件(.PPM):C++ 读取/写入PPM图像文件C++;,c++,ifstream,ofstream,ppm,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 = n
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;
}
我的值与实际文件相对应。因此,我高兴地尝试编写数据:
std::ostream& operator <<(std::ostream &outputStream, const PPMObject &other)
{
outputStream << "P6" << " "
<< other.width << " "
<< other.height << " "
<< other.maxColVal << " "
;
outputStream << other.m_Ptr;
return outputStream;
}
基于,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;
}
这段代码只写一个图像
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;
}
从inputStream提取时,不会将任何内容读入other.magicNum。它是否声明为字符串?这应该是因为我们想读“P6”。如果它是一个整数,编译器会很高兴。但是不会向成员变量中读取任何内容。这是正常的,因为文件以字符串“P6”开头。您是否显示了文件头?您的文件是否真的以“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;
}
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;
}
struct PPMObject
{
std::string magicNum;
int width, height, maxColVal;
char * m_Ptr;
};