C++语言BMP图像高度宽度和数据的读取
#include <stdio.h>
#include <malloc.h>
#include <iostream.h>
#include <stdlib.h>
void main()
{
FILE *fid, *newraw,*newhead,*newbmp;
char *ph=new char;
long int width;
long int height;
int a,b,c,d,m,n,i,j;
//打开lena_gray.bmp
if((fid=fopen("LENA2.bmp","rb+"))==NULL)
{
cout<<"cannot open file\n"<<endl;
exit(0);
}
//读取宽度和高度
fseek(fid,18,SEEK_SET);
fread(&width,sizeof(long),1,fid);
fread(&height,sizeof(long),1,fid);
cout<<"width="<<width<<endl;
cout<<"height="<<height<<endl;
//////////////////转化成表头和RAW文件/////////////////////////
//新建head文件(用于记录文件头和调色板)
if((newhead=fopen("newhead","wb+"))==NULL)
{
cout<<"cannot create newhead\n"<<endl;
exit(0);
}
//新建lena_gray.raw
if((newraw=fopen("lena_gray.raw","wb+"))==NULL)
{
cout<<"cannot create lena_gray.raw\n"<<endl;
exit(0);
}
fseek(fid,0L,SEEK_SET);
fread(ph,1078,1,fid);
fwrite(ph,1078,1,newhead);
fclose(newhead);
//对图像宽度进行处理:
if(width%4!=0)
{
width=(width*8+31)/32*4;
}
//申请二维数组的空间
char **p=new char*;
for(i=0;i<height;i++)
p=new char;
char **q=new char*;
for(j=0;j<height;j++)
q=new char;
fseek(fid,1078,SEEK_SET);
for(a=0;a<height;a++)
{
for(b=0;b<width;b++)
{
fread(&p,sizeof(char),1,fid);
}
}
//坐标转换
for(m=0;m<height;m++)
{
for(n=0;n<width;n++)
{
q=p;
}
}
for(c=0;c<height;c++)
{
for(d=0;d<width;d++)
{
fwrite(&q,sizeof(char),1,newraw);
}
}
fclose(newraw);
fclose(fid);
////////////////////////转化成BMP文件///////////////////
//新建bmp文件
if((newbmp=fopen("lena_nn.bmp","wb+"))==NULL)
{
cout<<"cannot create file\n"<<endl;
exit(0);
}
//打开newhead文件
if((newhead=fopen("newhead","rb+"))==NULL)
{
cout<<"cannot open file\n"<<endl;
exit(0);
}
//打开lena_gray.raw
if((newraw=fopen("lena_gray.raw","rb+"))==NULL)
{
cout<<"cannot open file\n"<<endl;
exit(0);
}
//向lena_nn.bmp写入文件头
fread(ph,1078,1,newhead);
fwrite(ph,1078,1,newbmp);
for(a=0;a<height;a++)
{
for(b=0;b<width;b++)
{
fread(&p,sizeof(char),1,newraw);
}
}
//转换坐标
for(m=0;m<height;m++)
{
for(n=0;n<width;n++)
{
q=p;
}
}
//向lenan.bmp文件写入图像数据
for(c=0;c<height;c++)
{
for(d=0;d<width;d++)
{
fwrite(&q,sizeof(char),1,newbmp);
}
}
fclose(newbmp);
fclose(newraw);
fclose(newhead);
//释放二维数组占用的空间
for(i=0;i<height;i++)
delete(p);
delete(p);
for(j=0;j<height;j++)
delete(q);
delete(q);
}
页:
[1]