首页 文章

C读/写PPM图像文件灰显图像

提问于
浏览
0

我正在尝试编写一个程序来读取ppm图像,将它们存储为对象,然后再将它们写出来 . 理想情况下,我想将像素存储为int类型的对象,但我只能使用chars获得相似的图像 . 不幸的是,即使使用char对象也会导致图像的灰色版本 . 我不确定为什么更改存储类型会导致如此大的变化,或者为什么在保留形状时图像颜色会丢失 .

我试图在这里查看无数的其他ppm程序问题,但我不能对他们的答案做出正面或反面(或者如果它们甚至是相关的) . 我对这种语言非常不熟悉,不知道会发生什么 .

如果有人能解释我做错了什么,以及我可能用来以int格式而不是char存储数据的策略,我将非常感激 .

下面是我的ppm类的文件读取和文件写入代码,我的main函数只是初始化一个ppm对象,调用readfile(),然后调用writefile() . 在其中的某处,它无法保留图像 .

void PPM::readFile(std::string filename)
{
    std::ifstream file;
    std::string stuff;
    char junk;
    file.open(filename, std::ios::binary);
    file >> stuff >> width >> height >> maxCol;
    file >> std::noskipws >> junk;
    int i = 0;
    char r, g, b;
    std::cout << width*height;
    while (i < width*height)
    {
        file.read(&r, 1);
        file.read(&g, 1);
        file.read(&b, 1);
        red.push_back(b);
        grn.push_back(b);
        blu.push_back(b);
        i++;
        std::cout << i << std::endl;
    }
}

void PPM::writeFile(std::string filename) const
{
    std::ofstream file;
    file.open(filename, std::ios::binary);
    file << "P6 " << width << " " << height << " " << maxCol << std::endl;
    int i = 0;
    std::cout << width << " " << height;
    while (i < width*height)
    {
        file.write(&red[i], sizeof(red[i]));
        file.write(&grn[i], sizeof(grn[i]));
        file.write(&blu[i], sizeof(blu[i]));
        std::cout << "iteration " << i << std::endl;
        i++;
    }
}

再次感谢您提供的任何帮助

1 回答

  • 1
    red.push_back(b);
    grn.push_back(b);
    blu.push_back(b);
    

    这是错误 . 你需要分别推回r,g和b . 同样将char更改为int,如下面的注释所指出的那样更安全 .

相关问题