我正在尝试将24位位图图像转换为灰度。

#include<iostream>
#include<fstream>
#include<conio.h>
#include<stdio.h>
using namespace std;
class pixel{
            public:
                   unsigned char b;
                   unsigned char g;
                   unsigned char r;
            void display()
            {
                 cout<<r<<" "<<g<<" "<<b<<" ";
                 }
      }p1;
using namespace std;
int main(){
    unsigned char avg;
    fstream file("image.bmp",ios::binary|ios::in|ios::out);

    int start;
    file.seekg(10);
    file.read((char*)&start,4);


    file.seekg(start);
    int i=0;
   while(!file.eof()){
                      cout<<file.tellg();//Remove this and the program doesn't work!
                     file.read((char*)&p1,3);
                     avg=(p1.b+p1.g+p1.r)/3;
                     p1.b=avg;
                     p1.g=avg;
                     p1.r=avg;
                     file.seekg(-3,ios::cur);
                     file.write((char*)&p1,3);
                       }
    file.close();
    getch();
    return 0;
}

当我删除cout tellg语句时,循环仅运行两次!

我不知道删除cout语句有什么区别?

结果:只有一个像素变为灰度。

我在这里找到了问题的简单版本

Reading and writing to files simultaneously?

但是没有找到解决方案...

最佳答案

在读写std::fstream时,在读写之间切换时需要查找。这样做的原因是文件流共享一个公共(public)的输入和输出位置。为了也支持有效的缓冲,必须将当前位置告知相应的其他缓冲。这是寻求工作的一部分。 tellg()搜索当前位置。

请注意,在读写之间切换是非常低效的,尤其是在实现得到优化的情况下。您最好写一个不同的文件或以合理大小的组更新值。

09-25 17:43