VC++创建BMP图像且保存

主要就是想pData中,写像素数据。
    char szFileName[32];
    time_t ltime;
    struct tm* pnow;
    HANDLE hFile;
    BYTE *pData = NULL;
    int i, j, n;
    BITMAPFILEHEADER bmfHdr;
    BITMAPINFOHEADER bi;
    DWORD dwBytesWrite;
	int width, height;
	BYTE qrData[MAX_MODULESIZE][MAX_MODULESIZE];
	//图像大小
	width = height = 100;

    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++)
    {
        pData[i] = 255;
    }

    //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, strFileName, 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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值