gpt4 book ai didi

c++ - 读取/写入 PPM 图像文件 C++

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:35:56 25 4
gpt4 key购买 nike

尝试以我知道的唯一方式读写 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;
}

逻辑错误:

我只写了图片的一部分。文件头或手动打开文件都没有问题。

类公共(public)成员变量:

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];

但是由于某种原因这会导致运行时错误..

最佳答案

基于 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;
};

关于c++ - 读取/写入 PPM 图像文件 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28896001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com