转自:http://m.blog.csdn.net/g200407331/article/details/52540478,亲测可行
灰度图像数据存在一块内存里,首地址为pData,宽度为iWidth,高度为iHeight,保存路径为qstrPath
由于bmp的第一行像素代表的其实是图像的最后一行像素,所以向bmp文件写入像素时,其实是倒着写
void vSaveImg(unsigned char * pData, int iWidth, int iHeight, QString qstrPath)
{
BITMAPFILEHEADER targetfileheader;
BITMAPINFOHEADER targetinfoheader;
memset(&targetfileheader, 0, sizeof(BITMAPFILEHEADER));
memset(&targetinfoheader, 0, sizeof(BITMAPINFOHEADER));
targetfileheader.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) + (DWORD)sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD);
targetinfoheader.biSize = iWidth * iHeight + sizeof(RGBQUAD) * 256 + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
targetfileheader.bfReserved1 = 0;
targetfileheader.bfReserved2 = 0;
targetfileheader.bfType = 0x4D42;
targetinfoheader.biBitCount = 8;
targetinfoheader.biSize = sizeof(BITMAPINFOHEADER);
targetinfoheader.biHeight = iHeight;
targetinfoheader.biWidth = iWidth;
targetinfoheader.biPlanes = 1;
targetinfoheader.biCompression = BI_RGB;
targetinfoheader.biSizeImage = 0;
targetinfoheader.biXPelsPerMeter = 0;
targetinfoheader.biYPelsPerMeter = 0;
targetinfoheader.biClrImportant = 0;
targetinfoheader.biClrUsed = 0;
RGBQUAD rgbquad[256];
int i;
for(i = 0; i < 256; i++)
{
rgbquad[i].rgbBlue = i;
rgbquad[i].rgbGreen = i;
rgbquad[i].rgbRed = i;
rgbquad[i].rgbReserved = 0;
}
FILE * fp = fopen(qstrPath.toLatin1().data(), "wb");
fwrite(&targetfileheader, sizeof(BITMAPFILEHEADER), 1, fp);
fwrite(&targetinfoheader, sizeof(BITMAPINFOHEADER), 1, fp);
fwrite(&rgbquad, sizeof(RGBQUAD), 256, fp);
for(i = 0; i < iHeight; i++)
{
fwrite(pData + (iHeight - 1 - i) * iWidth, iWidth, 1, fp);
}
fclose(fp);
}