C语言读取保存图像程序,但是有些问题,保存的图像不能显示,另外就是保存的图像比源图像要大很多,求大侠指导
#include <stdio.h>#include "Windows.h"
BOOL readBmp(char *bmpName);
BOOL saveBmp(char *bmpName, char *imgBuf, int width, int heigh, int biBitCount, RGBQUAD *pColorTable);
char *pBmpBuf; //位图数据
int bmpWidth; // 图像宽度
int bmpHeight; //图像高度
int biBiCount; //图像类型,每像素位数
RGBQUAD *pColorTable; //位图颜色表指针
int main()
{
char readName[] = "read.BMP";
readBmp(readName);
char writeName[] = "write.BMP";
saveBmp(writeName, pBmpBuf, bmpWidth, bmpHeight, biBiCount, pColorTable);
int lineByte = (bmpWidth*bmpHeight/8+3)/4*4;
if (biBiCount == 8)
{
for (int i = 0; i < bmpWidth/2; i++)
{
for (int j = 0; j < bmpHeight/2; j++)
{
*(pBmpBuf+i*lineByte+j) = 0;
}
}
}
else if (biBiCount == 24)
{/////对于24位真彩图,每个像素占三个字节分别存储R、G、B三个颜色分量的颜色值
for (int i = 0; i < bmpWidth/2; i++)
{
for (int j = 0; j < bmpHeight/2; j++)
{
for (int k = 0; k < 3; k++)
*(pBmpBuf+i*lineByte+j*3+k) = 0; //将rgb三个颜色分量设置成黑色
}
}
}
char Name[] = "copy.BMP";
saveBmp(Name, pBmpBuf, bmpWidth, bmpHeight, biBiCount, pColorTable);
delete []pBmpBuf;
if (biBiCount == 8)
{
delete []pColorTable;
}
return 0;
}
BOOL readBmp(char *bmpName )
{
FILE *pf = fopen(bmpName, "rb");
if (pf == NULL) return FALSE;
printf("read %s succeeded!\n", bmpName);
fseek(pf, sizeof(BITMAPFILEHEADER), SEEK_SET);
BITMAPINFOHEADER infoHeader;
fread(&infoHeader, sizeof(BITMAPINFOHEADER), 1, pf);
bmpWidth = infoHeader.biWidth;
bmpHeight = infoHeader.biHeight;
biBiCount = infoHeader.biBitCount;
//图像每行的字节数,一定要是4的倍数
int lineByte = (bmpWidth*bmpHeight/8+3)/4*4;
pBmpBuf = new char[lineByte*bmpHeight];
//灰度图像有颜色表
if (biBiCount == 8)
{
pColorTable = new RGBQUAD[256];
fread(pColorTable, sizeof(RGBQUAD), 1, pf);
}
fread(pBmpBuf, lineByte*bmpHeight, 1, pf);
fclose(pf); //关闭文件
return TRUE;
}
BOOL saveBmp(char *bmpName, char *imgBuf, int width, int heigh, int biBitCount, RGBQUAD *pColorTable )
{
FILE *pf = fopen(bmpName, "wb");
if (pf == NULL) return FALSE;
printf("write %s succeeded!\n", bmpName);
//写头文件
int colorTableSize = 0;
if (biBitCount == 8)
{
colorTableSize = 1024;
}
int lineByte = (width*heigh/8+3)/4*4;
BITMAPFILEHEADER filehead;
filehead.bfOffBits = 54+colorTableSize;
filehead.bfType = 0x4D42;
filehead.bfSize = sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+colorTableSize+lineByte*heigh;
filehead.bfReserved1 = 0;
filehead.bfReserved2 = 0;
fwrite(&filehead, sizeof(BITMAPFILEHEADER), 1, pf);
BITMAPINFOHEADER infoHead;
infoHead.biBitCount = biBitCount;
infoHead.biWidth = width;
infoHead.biHeight = heigh;
infoHead.biSize = 40;
infoHead.biClrImportant = 0;
infoHead.biSizeImage = lineByte*heigh;
infoHead.biClrUsed = 0;
infoHead.biPlanes = 1;
infoHead.biXPelsPerMeter = 0;
infoHead.biYPelsPerMeter = 0;
fwrite(&infoHead,sizeof(BITMAPINFOHEADER), 1, pf);
if (biBitCount == 8)
{
fwrite(pColorTable, sizeof(RGBQUAD), 256, pf);
}
fwrite(pBmpBuf, lineByte*heigh, 1, pf);
fclose(pf);
return TRUE;
}