读写24位BMP图片的问题

c_tianzi 2012-01-13 07:47:22
读写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;
}
...全文
114 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
c_tianzi 2012-01-16
  • 打赏
  • 举报
回复
图像倾斜,是宽度不是4的倍数,需要补齐的问题,出现颜色变成灰色,是颜色值没有完全读出。
觅食的猫猫 2012-01-14
  • 打赏
  • 举报
回复
24位的没有调色板
幻氵落 2012-01-14
  • 打赏
  • 举报
回复
貌似得4的倍数,不是很清楚

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧