file.Open(lpszPathName,CFile::modeCreate||CFile::modeReadWrite);逻辑或改成file.Open(lpszPathName,CFile::modeCreate|CFile::modeReadWrite);按位或
#include
BOOL SaveBmpFile(LPCTSTR lpszPathName, long imageHeight, long imageWidth, int ColorBits, void * m_pBits)
{
long lTotal = 0;
int i;
BOOL ret = TRUE;
CFile file;
if ( !file.Open( lpszPathName, CFile::modeCreate | CFile::modeReadWrite) )
{
_tprintf( TEXT("Can't open file %s\n"), lpszPathName);
return FALSE;
}
BITMAPFILEHEADER bmpFH;
bmpFH.bfType = 0x4d42; // 'MB'
bmpFH.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + sizeof(tagRGBQUAD) * (ColorBits <= 8 ? (1 << ColorBits) : 0);
bmpFH.bfSize = bmpFH.bfOffBits + (((imageWidth * ColorBits + 31) & ~31) >> 3) * imageHeight;
bmpFH.bfReserved1 = 0;
bmpFH.bfReserved2 = 0;
LPBITMAPINFO lpbmi = (LPBITMAPINFO)new BYTE[sizeof(BITMAPINFO) + 4 * (1 << 8)];
lpbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
lpbmi->bmiHeader.biWidth = imageWidth;
lpbmi->bmiHeader.biHeight = imageHeight;
lpbmi->bmiHeader.biPlanes = 1;
lpbmi->bmiHeader.biBitCount = ColorBits;
lpbmi->bmiHeader.biCompression = BI_RGB;
lpbmi->bmiHeader.biSizeImage = (((imageWidth * ColorBits + 31) & ~31) >> 3) * imageHeight;
lpbmi->bmiHeader.biXPelsPerMeter = 3000;
lpbmi->bmiHeader.biYPelsPerMeter = 3000;
lpbmi->bmiHeader.biClrUsed = 0;
lpbmi->bmiHeader.biClrImportant = 0;
for(i = 0; i < 256; i++)
{
lpbmi->bmiColors[i].rgbBlue = i;
lpbmi->bmiColors[i].rgbGreen = i;
lpbmi->bmiColors[i].rgbRed = i;
lpbmi->bmiColors[i].rgbReserved = 0;
}
switch(ColorBits)
{
case 1:
case 4:
case 8:
file.Write(&bmpFH, sizeof(BITMAPFILEHEADER));
file.Write(lpbmi, sizeof(BITMAPINFOHEADER));
file.Write(lpbmi->bmiColors, sizeof(tagRGBQUAD) * (1 << ColorBits)); // 调色板
file.Write(m_pBits, lpbmi->bmiHeader.biSizeImage);
break;
case 16:
case 24:
case 32:
file.Write(&bmpFH, sizeof(BITMAPFILEHEADER));
file.Write(lpbmi, sizeof(BITMAPINFOHEADER));
file.Write(m_pBits, lpbmi->bmiHeader.biSizeImage);
break;
default:
ret = FALSE;
}
file.Close();
delete [] (BYTE *)lpbmi;
return ret;
}
int main()
{
char buf[60000];
int i;
for(i=0; i<60000; i++) buf[i] = (char) rand();
SaveBmpFile("3.bmp", 200, 300, 8, buf);
return 0;
}