本文为答复论坛回复所写,运行环境WINXP+TurboC2.0,图片来源C:\WINDOWS\winnt256.bmp,因为该BMP不规范调色板没有256个,文件尾部多了两个0字节,用UltraEdit删去了最后两个字节,同时修改表示文件大小的第三个字节28 BE 00 00为26 BE 00 00。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dos.h>
#include <fcntl.h>
void initVGAMode(unsigned char mode)
{
union REGS inregs,outregs;
inregs.h.ah = 0;
inregs.h.al = mode;
int86(0x10, &inregs, &outregs);
}
void setVGAPalette(unsigned char index, unsigned char red, unsigned char green, unsigned char blue)
{
outp(0x3c6, 0xff);
outp(0x3c8, index);
outp(0x3c9, red >> 2);
outp(0x3c9, green >> 2);
outp(0x3c9, blue >> 2);
}
unsigned char header[] =
{
0x42, 0x4D, 0xAA, 0xAA, 0xAA, 0xAA, 0x00, 0x00, /* 2 AA->FileSize */
0x00, 0x00, 0xBB, 0xBB, 0xBB, 0xBB, 0x28, 0x00, /* 10 BB->OffBits */
0x00, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xDD, 0xDD, /* 18 CC->Width */
0xDD, 0xDD, 0x01, 0x00, 0xEE, 0xEE, 0x00, 0x00, /* 22 DD->Height */
0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, /* 28 EE->BitCount */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 34 FF->ImageSize */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
struct
{
unsigned char blue;
unsigned char green;
unsigned char red;
unsigned char reserved;
} palette[256];
struct
{
unsigned long filesize;
unsigned long offbits;
unsigned long imagewidth;
unsigned long imageheight;
unsigned short bitcount;
unsigned long imagesize;
unsigned long widthbyte;
} bitmap;
unsigned char rowbuf[320];
void loadBitmap(const char * bmppath)
{
unsigned char far *ptr;
int i, j, left, top, width, height;
FILE *file = NULL;
do
{
if(bmppath == NULL) break;
file = fopen(bmppath, "rb");
if(file == NULL) break;
fread(header, 1L, sizeof(header), file);
if(header[0] != 0x42) break; /* B */
if(header[1] != 0x4D) break; /* M */
memcpy(&bitmap.filesize, header + 2, 4);
memcpy(&bitmap.offbits, header + 10, 4);
memcpy(&bitmap.imagewidth, header + 18, 4);
memcpy(&bitmap.imageheight, header + 22, 4);
memcpy(&bitmap.bitcount, header + 28, 2);
memcpy(&bitmap.imagesize, header + 34, 4);
bitmap.widthbyte = (bitmap.imagewidth * bitmap.bitcount + 31) / 32 * 4;
if(bitmap.bitcount != 8) break;
fread(palette, 256L, 4L, file);
for(i = 0; i < 256; i++)
{
setVGAPalette(i, palette[i].red, palette[i].green, palette[i].blue);
}
width = min(320, bitmap.imagewidth);
height = min(200, bitmap.imageheight);
left = (320 - width) / 2;
top = (200 - height) / 2;
for(i = 0; i < height; i++)
{
fseek(file, -(i + 1) * bitmap.widthbyte, SEEK_END);
fread(rowbuf, width, 1L, file);
for(j = 0; j < width; j++)
{
ptr = MK_FP(0xA000, 320 * (top + i) + (left + j));
*ptr = rowbuf[j];
}
}
} while(0);
if(file) fclose(file);
}
int main()
{
initVGAMode(0x13);
loadBitmap("C:\\turboc2\\test.bmp");
getch();
initVGAMode(0x03);
return 0;
}
![](http://hi.csdn.net/attachment/201112/27/0_1324975182Sl66.gif)