尝试以我知道的方式读取和写入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;
}
逻辑错误:
我只写了一部分图像 . Headers 没有问题或手动打开文件 .
类公共成员变量:
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];
但由于某种原因,这会导致运行时错误 .
1 回答
基于http://fr.wikipedia.org/wiki/Portable_pixmap,P6是二进制图像 . 这会读取单个图像 . 请注意,不执行检查 . 这需要添加 .
此代码写入单个图像 .
m_Ptr仅包含RGB像素值 .
我在我从网上下载的图像(http://igm.univ-mlv.fr/~incerti/IMAGES/COLOR/Aerial.512.ppm)上测试了代码,并使用了以下结构PPMObject .