尝试以我知道的唯一方式读取和写入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;
}
我的值对应于实际文件。所以我乐意尝试写数据:
std::ostream& operator <<(std::ostream &outputStream, const PPMObject &other)
{
outputStream << "P6" << " "
<< other.width << " "
<< other.height << " "
<< other.maxColVal << " "
;
outputStream << other.m_Ptr;
return outputStream;
}
我确保使用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;
}
逻辑错误:
我只是写一部分图像。标题没有问题或手动打开文件。
类公共成员变量:
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];
但由于某种原因,这会导致运行时错误。
答案 0 :(得分:6)
基于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;
}
此代码会写入单个图像。
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;
}
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;
};