As it is descriped in the title. The code is shown as below
#include <Windows.h>
#include <string>
using namespace std;
#define WIDTH 90
#define HEIGHT 180
class Test {
public:
static bool ShowWithBMP(string filename) {
BITMAPFILEHEADER bmfh; // bitmap file header
BITMAPINFOHEADER bmih; // bitmap info header (windows)
const int OffBits = 54;
bmfh.bfReserved1 = 0;
bmfh.bfReserved2 = 0;
bmfh.bfType = 0x4d42; //"BM"
bmfh.bfOffBits = OffBits;
bmfh.bfSize = WIDTH * HEIGHT * 3 + OffBits;
memset(&bmih, 0, sizeof(BITMAPINFOHEADER));
bmih.biSize = 40;
bmih.biPlanes = 1;
bmih.biSizeImage = 0;
bmih.biBitCount = 24;
bmih.biCompression = BI_RGB;
bmih.biWidth = WIDTH;
bmih.biHeight = HEIGHT;
FILE* file = fopen(filename.c_str(), "w");
fwrite((const void*)&bmfh, sizeof(BITMAPFILEHEADER), 1, file);
fwrite((const void*)&bmih, sizeof(BITMAPINFOHEADER), 1, file);
for (int row = 0; row < HEIGHT; ++row)
{
// RGB 24 BITS
for (int col = 0; col < WIDTH; ++col)
{
int index = row * WIDTH + col;
RGBTRIPLE pix;
pix.rgbtRed = 0;
pix.rgbtGreen = 0;
pix.rgbtBlue = 0;
fwrite((const void*)&pix, sizeof(RGBTRIPLE), 1, file);
}
}
fclose(file);
return true;
}
};
int main() {
Test::ShowWithBMP("test.bmp");
system("pause");
return 0;
}
When I set WIDTH to 90 and HEIGHT to 180, the output file "test.bmp" seems to be a wrong file and I can't open it, but when set WIDTH to 100 and HEIGHT to 180, it becomes correct. What's wrong with it? Is there any limitation when I try to write a bmp file with C++?