从bmp文件读取RGB像素 [英] Reading RGB pixels from bmp file

查看:845
本文介绍了从bmp文件读取RGB像素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小的bmp文件,如果R,G和B都不都是零,我想获取每个像素的RGB值并将这些值输出到txt文件中.我写了下面的程序;它可以正确读取标头数据,但不会显示RGB值.我认为我在for循环中做错了事.

I have a small bmp file and I want to get the RGB values of each pixel and output those values into a txt file if R, G, and B aren't all zero. I wrote the following program; it reads the header data correctly, but the RGB values aren't coming up. I assume I did something wrong in the for loop.

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

int main()
{
ifstream ifs;
ofstream ofs;
char input[80];
char output[80];

cout<<"Input file name"<<endl;
cin>>input;
ifs.open(input, ios::binary);

if(!ifs)
{
    cout<<"Error in opening file"<<endl;
    system("pause");
    return 0;
}

cout<<"Output file name"<<endl;
cin>>output;
ofs.open(output, ios::binary);

ifs.seekg(2);

int file_size;
ifs.read((char*)&file_size, sizeof(int));

ofs<<"Bitmap size: "<<file_size<<"\r\n";

ifs.seekg(10);
int beg;
ifs.read((char*)&beg, sizeof(int));

ofs<<"Beggining of image: "<<beg<<"\r\n";

ifs.seekg(18);
int columns;
ifs.read((char*)&columns, sizeof(int));

ofs<<"Column number: "<<columns<<"\r\n";

ifs.seekg(22);
int rows;
ifs.read((char*)&rows, sizeof(int));

ofs<<"Row number: "<<rows<<"\r\n";

int image_size=0;
columns+=(3*columns)%4;
image_size=3*columns*rows;

ofs<<"Size of image"<<image_size<<"\r\n";

ifs.seekg(beg);

unsigned char R,G,B;
for(int i=0; i<image_size; i+=3)
{
    ifs.read((char*)&B, sizeof(unsigned char));
    ifs.read((char*)&G, sizeof(unsigned char));
    ifs.read((char*)&R, sizeof(unsigned char));

    if(R!=0 || G!=0 || B!=0)
    ofs<<"R: "<<R<<" G: "<<G<<" B: "<<B<<"  position in file: "<<ifs.tellg()<<"\r\n";
}


system("pause");
    return 0;


}

推荐答案

我运行了代码,它运行良好,我想您是说"RGB值没有增加",您没有看到整数值,其中可以解决的情况:

I ran the code and it works fine, I presume you mean by 'RGB values aren't coming up' you are not seeing the integer values, in which case this will fix it:

ofs<<"R: "<<int(R)<<" G: "<<int(G)<<" B: "<<int(B)<<"  position in file: "<<ifs.tellg()<<"\r\n";

更新:我之前发布过,您可以将ifs.read()替换为ifs >> R >> G >> B;正如@Benjamin Lindley指出的那样,这是不正确的,因为>>运算符用于格式化的文本,而不是二进制的.这意味着,如果文件包含例如空格/换行符/等字符,则操作员将跳过该文件并获取下一个字符.在这种简单情况下,最好使用ifs.get(char).

Update: I posted earlier that you could replace ifs.read() with ifs >> R >> G >> B; As @Benjamin Lindley points out, this is incorrect as the >> operator is for formatted text, not binary. This means if the file contains eg a space/newline/etc character, the operator will skip it and take the next char. Better to use ifs.get(char) in this simple case.

这篇关于从bmp文件读取RGB像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆