我正在尝试将 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;
}
当我删除 couttellg 语句时,循环仅运行两次!
我不明白删除 cout 语句有什么区别?
结果:只有一个像素变为灰度。
我在这里找到了问题的更简单版本
同时读取和写入文件? https://stackoverflow.com/questions/2797125/reading-and-writing-to-files-simultaneously
但没找到解决办法...
当读和写一个std::fstream
在读取和写入之间切换时需要进行查找。原因是文件流共享公共输入和输出位置。为了还支持有效的缓冲,有必要向相应的其他缓冲区通知当前位置。这是搜索所做的一部分。tellg()
查找当前位置。
请注意,在读取和写入之间切换效率非常低,尤其是在实现优化良好的情况下。您最好编写不同的文件或更新合理大小的组中的值。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)