Reputation: 2626
This is my second month since I've started C/C++ programming. I want to create a random BMP image. I did some research about the way of creating such a file, and I came up with this code:
#pragma pack(push,1)
struct PixelBMP
{
uint8_t higher:4;
uint8_t lower:4;
}pxl;
#pragma pack(pop)
#pragma pack(push,1)
struct BMPHEADER
{
char BM[2]={'B','M'};
uint32_t Size = 54+360000;
uint16_t Reserved1 = 0;
uint16_t reserved2 = 0;
uint32_t offBits = 54;
}BMPHEADERFILE;
#pragma pack(pop)
#pragma pack(push,1)
struct BMPINFOHEADER
{
uint32_t infoHsize = 40;
uint32_t width = 600;
uint32_t height = 600;
uint16_t planes = 1;
uint16_t bitCount = 4;
uint32_t compression = 0;
uint32_t biSizeImage = 0;
uint32_t meter = 3780;
uint32_t vertical = 3780;
uint32_t crlUsed =0;
uint32_t crlImp = 0;
}BMPINFOHEADERFILE;
#pragma pack(pop)
void create_bmp()
{
FILE *output_file;
output_file = fopen("generated_img.bmp", "wb");
if(output_file==NULL)
{
perror("Error while opening the file ");
exit(1);
}
fwrite(&BMPHEADERFILE, sizeof(BMPHEADERFILE), 1, output_file);
fwrite(&BMPINFOHEADERFILE, sizeof(BMPINFOHEADERFILE), 1,output_file);
size_t bmp_size = BMPINFOHEADERFILE.width*BMPINFOHEADERFILE.height;
for(int i=0;i<bmp_size;i++)
{
pxl.lower = rand()%17;
pxl.higher = rand()%17;
fwrite(&pxl, sizeof(pxl),1,output_file);
}
fclose(output_file);
}
int main()
{
create_bmp();
return 0;
}
For some reason, the bmp file generated, cannot be open. I get some error from Windows. I have windows 10. PS: I also ran the code from this source, and it gave me the same error when I tried to open it.
Can anybody help me with a hint? Thank you very much! I much appreciate your time!
UPDATE: I have done one first edit, and it seems to work, my bmp image is generated. It has weird colours, but I think it works. In regard with bits per pixel, I need to use 16 colours palete, using 4 bit mode.
Upvotes: 1
Views: 1424
Reputation: 22012
BMPINFOHEADERFILE.bitCount
to 24
, not 4
.struct BMPHEADER
may be padded and word-aligned after char BM[2]
,
which causes misalignment of the bitmap file format.
To avoid this, say struct __attribute__ ((__packed__)) BMPHEADER {..}
.BMPHEADERFILE.Size
should be 54+270000
, not 52+270000
.rand() % 17
generates the pixel values
between 0 and 17, which will be too dark to see. rand() % 256
might
be better in terms of visibility.Upvotes: 1