// CreateBmp24.c
#include <stdio.h> #include <windows.h> #include <time.h>
void CreateBmp24(unsigned int width, unsigned int height);
int main(int argc, char **argv) { int width; int heigth;
if ( argc != 3) { printf("Usage %s width height/n", argv[0]); printf("Example:/n/t%s 16 16/n", argv[0]); return -1; }
// get the width and height from the command line
width = atoi(argv[1]); heigth = atoi(argv[2]);
CreateBmp24(width, heigth);
return 0; }
void CreateBmp24(unsigned int width, unsigned int height) { char szFileName[32]; time_t ltime; struct tm* pnow; HANDLE hFile; BYTE *pData = NULL; int i, num; BITMAPFILEHEADER bmfHdr; BITMAPINFOHEADER bi; DWORD dwBytesWrite;
if ( width <= 0 || height <= 0 ) return;
// allocate memory for data area
pData = (BYTE*)malloc(width * height * 3); if ( pData == NULL ) return;
// generate random data
srand((unsigned)time(NULL)); for ( i = 0; i < (int)(width * height * 3); i++) { do { num = rand( ); // generate number between 0 and 255
} while (num < 0 || num > 255); pData[i] = num; }
// initialize the structures
RtlZeroMemory(&bmfHdr, sizeof(bmfHdr)); RtlZeroMemory(&bi, sizeof(bi));
// fill the necessary struct fields of the BITMAPFILEHEADER
bmfHdr.bfType = 0x4d42; // "BM"
bmfHdr.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + width * height * 3; bmfHdr.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
// fill the necessary struct fields of the BITMAPINFOHEADER
bi.biSize = sizeof(bi); bi.biBitCount = 24; bi.biHeight = height; bi.biWidth = width; bi.biCompression = BI_RGB; bi.biPlanes = 1;
/* according current date and time to generate file name, saved in c:/ */ time(<ime); pnow = localtime(<ime); wsprintf(szFileName, "C://%04d%02d%02d-%02d%02d%02d.bmp", pnow->tm_year, pnow->tm_mon, pnow->tm_mday, pnow->tm_hour, pnow->tm_min, pnow->tm_sec);
// create the bmp file
hFile = CreateFile(szFileName, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if ( hFile == INVALID_HANDLE_VALUE ) { free(pData); return; }
// write the BITMAPFILEHEADER
WriteFile(hFile, &bmfHdr, sizeof(BITMAPFILEHEADER), &dwBytesWrite, NULL); // write the BITMAPINFOHEADER
WriteFile(hFile, &bi, sizeof(BITMAPINFOHEADER), &dwBytesWrite, NULL); // write the bmp data
WriteFile(hFile, pData, width * height * 3, &dwBytesWrite, NULL); // release resources
CloseHandle(hFile); free(pData);
printf("The bmp file is %s/n", szFileName); }
|