taigi tanaka
taigi tanaka

Reputation: 299

Importing bmp file in C++

I have looked at numerous tutorials but I just can't make the Pixel data reading work...

Here is what I have got so far:

struct RGB
{
 unsigned char blue,green,red,reserved;
};

BmpLoader* loadBmp(const char* filename)
{
BITMAPFILEHEADER header;
BITMAPINFOHEADER info;
FILE *file;
file=fopen(filename,"rb");

fread(&header,sizeof(header),1,file);
fread(&info,sizeof(info),1,file);
unsigned char *px;
int bitsize=info.biWidth*info.biHeight;
px=new unsigned char[bitsize*3];
fseek(file,header.bfOffBits,0);
for(int i=0;i<bitsize;i++)
{
    RGB rgb;
    fread(&rgb,sizeof(RGB),1,file);
    px[i*3]=rgb.red;
    px[i*3+1]=rgb.green;
    px[i*3+2]=rgb.blue;
    printf("%d %d %d\n",px[i*3],px[i*3+1],px[i*3+2]);

}

    return new BmpLoader(px,info.biWidth,info.biHeight);

}

As you can see I have also tried to print them as decimals which should have given the ascii code of the characters and the output looks like this :

204 204 76
204 204 255
204 204 136
204 204 76
204 204 255
204 204 136

My question is : How can I fix this? What am I exactly doing wrong?

Upvotes: 0

Views: 2158

Answers (1)

john
john

Reputation: 87944

You are only reading one byte into rgb

fread(&rgb,1,1,file);

should be

fread(&rgb,sizeof(RGB),1,file);

Upvotes: 2

Related Questions