YetAnotherOldBoy
YetAnotherOldBoy

Reputation: 47

bitmap display not correct

tagBITMAPFILEHEADER bh;
BITMAPINFOHEADER bih;
char buf[3];
unsigned char bmp[200][600];
int width ,height;
ifstream fin(L"D:\\xx\\3.bmp",ios::_Nocreate|ios::binary);
fin.read((char*)&bh,sizeof(bh));
fin.read((char*)&bih,sizeof(bih));


width=bih.biWidth;
height=bih.biHeight;
HWND myconsole=GetConsoleWindow();
HDC mydc=GetDC(myconsole);

for(int i=height;i>=1;i--)
    for(int j=1;j<=width;j++)
    {
        fin.read(buf,sizeof(buf));
        bmp[i][j*3]=buf[0];
        bmp[i][j*3+1]=buf[1];
        bmp[i][j*3+2]=buf[2];

    }
    for(int i=1;i<=height;i++)
    {
        for(int j=1;j<=width;j++)
        {
            COLORREF color;
            color=RGB(bmp[i][j*3],bmp[i][j*3+1],bmp[i][j*3+2]);
            SetPixel(mydc,j,i,color);
        }
        //cout<<width<<endl;
    }
    ReleaseDC(myconsole,mydc);
fin.close();
return 0;

source bmp display like this

i read pixel to an array, this bmp's bitcount is 24, so i use a char[3] to store the data, but finaly display on the console like this,i can't figure it out.

Upvotes: 0

Views: 79

Answers (1)

Jonathan Potter
Jonathan Potter

Reputation: 37202

Bitmap image data rows must be aligned on a 32-bit boundary. You therefore have to calculate the amount of padding that you need and skip that number of bytes at the end of every row.

In general the formula to calculate the number of bytes per row and the number you must skip is:

int rowBytes = ( (width * bytes_per_pixel) + 3 ) & ~3;
int skipBytes = rowBytes - (width * bytes_per_pixel);

Then skip skipBytes at the end of every row when reading the file.

Upvotes: 4

Related Questions