256色位图名目与256色位图编程
下面就一个C++措施(DrawBmp.cpp, Borland C++ Builder 6.0 编译运行通过)详细阐明
//—————————————————————————
#include <vcl.h>
#pragma hdrstop
#include "DrawBitmap.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
typedef enum // 界说显示位图操纵的执行功效
{
OK, //乐成
FORMATERROR, // 文件名目错误
FILENOTFOUND, //文件未打开
OVERFLOW, // 内存溢出
READERROR // 读文件错误
}RESULTCODE;
RESULTCODE DrawBmp(int start_x, int start_y, char filename[]); //显示位图函数界说
AnsiString filen; // 需要显示的文件名称
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
filen = InputBox("256位图显示措施","输入256位图文件名称...",filen);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormPaint(TObject *Sender)
{
RESULTCODE res = DrawBmp(0,0,filen.c_str());
}
#include "stdio.h"
unsigned char DAC[256][3]; // 颜色转换矩阵
RESULTCODE DrawBmp(int start_x, int start_y, char filename[])
{
int i,j,k,n,r,g,b,width,length;
int xcnt = 0,ycnt = 0;
FILE *fp;
if((fp=fopen(filename,"rb"))==NULL) // 打开位图文件
{
ShowMessage("文件打开失败");
return FILENOTFOUND;
}
fseek(fp,28,SEEK_SET); // 前28字节为位图文件头根基信息
fread(&i,2,1,fp); // 29,30字节为位图色深位数
if(i!=8) /*查抄是否为256色位图*/
{
fclose(fp);
return FORMATERROR;
}
fseek(fp,18,SEEK_SET);
fread(&width,4,1,fp); // 19,20,21,22 存储位图宽度
fread(&length,4,1,fp); // 23,24,25,26 存储暗示位图长度
fseek(fp,54,SEEK_SET); // 54字节之后为位图颜色转换矩阵部门
for(i=0;i<256;i++)
{
DAC[i][0] = fgetc(fp);
DAC[i][1] = fgetc(fp);
DAC[i][2] = fgetc(fp); /*获取R、G、B分量, 放到颜色转换表中*/
fgetc(fp); //保存位, 不利用
}
Form1->Height = length+30; //配置窗体显示属性, 按位图巨细调解窗体巨细与位置
Form1->Width = width;
Form1->Left = (1024 - Form1->Width)/2; // 合用显示判别率 1024 * 768
Form1->Top = (768 - Form1->Height)/2;
ycnt = start_y+length;
unsigned char *buffer; // 配置输出缓冲
buffer = (unsigned char *)malloc(width); //分派行输出所需空间到缓冲
if (!buffer)
{
return OVERFLOW;
}
while (ycnt > 0)
// ycnt, xcnt 为点阵计数器, 位图与显示屏幕的坐标系统存在不同, ycnt //也用于坐标转换
{
xcnt = 0;
if (fread(buffer,width,1,fp) != 1) // 读一行
{
return READERROR;
}
while (xcnt < width) // 行内扫描各点,影射到显示器
{
unsigned char data = buffer[xcnt];
// 查找颜色转换表, 输出点阵到窗体
Form1->Canvas->Pixels[xcnt][ycnt] =
RGB( DAC[data][2],DAC[data][1],DAC[data][0]);
xcnt++;
}
ycnt--;
}
fclose(fp);
return OK;
}
//—————————————————————————