读写256色的没有出问题,但是24位的时候,个别出现图像倾斜的问题,而且图片宽度也会发生变化,比如518*696会变成520*696,不知道为什么,求解答??
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <malloc.h>
#define WIDTHBYTES(i) ((i+31)/32*4)
//#pragma warning(disable: 4996)
int main()
{
BITMAPFILEHEADER bf; //BMP文件头结构体
BITMAPINFOHEADER bi; //BMP信息头结构体
FILE* fp; //指向文件的指针
RGBQUAD *ipRGB; //如果bi.biBitCount<24,有调色板的存在
DWORD LineByte,ImgSize;
DWORD NumColors;
unsigned char * * Imgdata;
int i,j;
char fileName[256];
int offset;
printf("please enter filename:");
scanf("%s",fileName);
fp=fopen(fileName,"rb");
if(fp == NULL)
{
printf("Open file error!");
exit(0);
}
//读取文件,信息头
fread(&bf,sizeof(BITMAPFILEHEADER),1,fp); //把指针fp所指向的文件的头信息写入bf(地址)
fread(&bi,sizeof(BITMAPINFOHEADER),1,fp);
LineByte=(DWORD)WIDTHBYTES(bi.biWidth*bi.biBitCount); //计算位图的实际宽度并确保它为32的倍数
ImgSize=(DWORD)LineByte*bi.biHeight;
if (bi.biClrUsed != 0 ) //位图实际使用的彩色表中的颜色索引数(设为0的话,则说明使用所有调色板项)
NumColors=(DWORD)bi.biClrUsed;
else
switch (bi.biBitCount)
{
case 1:NumColors=2;break;
case 4:NumColors=16;break;
case 8:NumColors=256;break;
case 24:NumColors=0;break;
}
//分配调色板内存
if(bi.biBitCount!=24)
{
ipRGB=(RGBQUAD *)malloc(NumColors*sizeof(RGBQUAD));
fread(ipRGB,sizeof(RGBQUAD),NumColors,fp);
}
Imgdata=new unsigned char*[bi.biHeight]; //声明一个指针数组
if(bi.biBitCount==24)
{
if(bi.biWidth%4!=0)
{
offset=4-bi.biWidth%4;
bi.biWidth=bi.biWidth+offset;
}
else
offset=0;
fseek(fp, 4, SEEK_CUR);//sizeof(RGBQUAD)
for ( i=(bi.biHeight)-1;i>=0;i--)
Imgdata[i]=new unsigned char[bi.biWidth]; //每个数组元素也是一个指针数组
for ( i=(bi.biHeight)-1;i>=0;i--)
for(j=0;j<bi.biWidth;j++)
fread(&Imgdata[i][j],3,1,fp);//每次只读取一个1字节,存入数组
}
else
{
for ( i=(bi.biHeight)-1;i>=0;i--)
Imgdata[i]=new unsigned char[bi.biWidth*3]; //每个数组元素也是一个指针数组
for ( i=(bi.biHeight)-1;i>=0;i--)
for(j=0;j<bi.biWidth*3;j++)
fread(&Imgdata[i][j],1,1,fp);//每次只读取一个1字节,存入数组
}
fclose(fp);
//写入另一个文件
fp=fopen("mybmp.bmp","wb");
fwrite(&bf,sizeof(BITMAPFILEHEADER),1,fp);
fwrite(&bi,sizeof(BITMAPINFOHEADER),1,fp);
if(bi.biBitCount!=24)
{
fwrite(ipRGB,sizeof(RGBQUAD),NumColors,fp); /////////////////
for (i=(bi.biHeight)-1 ;i>=0;i--)
for (j=0 ;j<bi.biWidth*3;j++)
{
Imgdata[i][j] =255-Imgdata[i][j];
fwrite(&Imgdata[i][j],1,1,fp);
}
}
else
{
fseek(fp, 4, SEEK_CUR);//sizeof(RGBQUAD)
for (i=(bi.biHeight)-1 ;i>=0;i--)
for (j=0 ;j<bi.biWidth;j++)
{
Imgdata[i][j] =255- Imgdata[i][j];
fwrite(&Imgdata[i][j],3,1,fp);
}
}
fclose(fp);
free(Imgdata);
return 0;
}