用C语言读取像素数据:
int ReadPixelData(char *filepath,BYTE *imgData)
{
BITMAPINFOHEADER bmih;
BITMAPFILEHEADER bmfh;
BYTE *data;
FILE *fp;
int n;
int width;
int height;
int bitCount;
DWORD dwLineBytes;
//读入文件头
n=ReadFileHeader(filepath,&bmfh);
if(n==-1)
{
printf("Can not read the file header of the BMP file.\n");
return -1;
}
//读入信息头
n=ReadInfoHeader(filepath,&bmih);
if(n==-1)
{
printf("Can not read the info header of the BMP file.\n");
return -1;
}
//获得信息头中有用数据
width=bmih.biWidth;
height=bmih.biHeight;
bitCount=bmih.biBitCount;
dwLineBytes=GetLineBytes(width,bitCount);
//检查分配的空间是否正确
if(_msize(imgData)!=(dwLineBytes*height))
{
printf("The size you allocate for the pixel data is not right.\n");
printf("Fittable size: %ld bytes.\n",(dwLineBytes*height));
printf("Your size: %ld bytes.\n",sizeof(imgData));
return -1;
}
//建立一个中间的变量
data=(BYTE*)malloc(dwLineBytes*height*sizeof(BYTE));
if(!data)
{
printf("Can not allocate memory for the pixel data.\n");
return -1;
}
//打开文件
fp=fopen(filepath,"rb");
if(!fp)
{
printf("Can not open the file: %s\n",filepath);
free(data);
return -1;
}
if(bitCount==8)
{//如果为8位位图
fseek(fp,bmfh.bfOffBits,SEEK_SET);//直接跳到像素数据
}
else if(bitCount==24)
{//与上面重复,可以只写一处
fseek(fp,bmfh.bfOffBits,SEEK_SET); //直接跳到像素数据
}
else
{
printf("Only Support: 8 or 24 bits.\n");
free(data);
fclose(fp);
return -1;
}
//读入像素数据,大小为高度乘上每行所占字节数
if(fread(data,dwLineBytes*height*sizeof(BYTE),1,fp)!=1)
{
printf("Can not read the pixel data.\n");
free(data);
fclose(fp);
return -1;
}
//拷贝读入的数据给imgData
memcpy(imgData,data,dwLineBytes*height*sizeof(BYTE));
//释放分配的中间变量的内存
free(data);
fclose(fp);//关闭文件
return 0;
}
用C语言读取位图的像素值:
void PrintPixelData(BYTE *imgData,int width,int height,int bitCount)
{
int i;
int j;
int p;
DWORD dwLineBytes=GetLineBytes(width,bitCount);
if(bitCount==8)
{//如果是8位位图
for(i=0;i<height;i++)
{
for(j=0;j<width;j++)
{
//读取灰度值
p=*(imgData+dwLineBytes*(height-1-i)+j);
printf("%d,",p);
}
printf("\n");
}
}
else if(bitCount==24)
{//如果是24位位图
for(i=0;i<height;i++)
{
for(j=0;j<width*3;j++)
{
printf("(");
//读取蓝色分量
p=*(imgData+dwLineBytes*(height-1-i)+j);
printf("%d,",p);
j++;
//读取绿色分量
p=*(imgData+dwLineBytes*(height-1-i)+j);
printf("%d,",p);
j++;
//读取红色分量
p=*(imgData+dwLineBytes*(height-1-i)+j);
printf("%d) ",p);
}
printf("\n");
}
}
else
{
printf("Only supported: 8 or 24 bits.\n");
}
}