本人在用VS2019进行bmp文件读取与存储时,彩色图像的输出图像与输入图像之间发生了偏移,但是灰度图像没有影响,请问是什么原因,代码如下
#include<Windows.h>
#include<stdio.h>
#include<iostream>
using namespace std;
unsigned char* pBmpBuf;//读入图像数据的指针
int bmpWidth;//图像的宽
int bmpHeight;//图像的高
RGBQUAD* pColorTable;//颜色表指针
int biBitCount;//图像类型
bool readBmp(char* bmpName)
{
FILE* fp = fopen(bmpName, "rb");
if (fp == 0) return 0;
fseek(fp, sizeof(BITMAPFILEHEADER), 0);
BITMAPINFOHEADER head;
fread(&head, sizeof(BITMAPINFOHEADER), 1, fp);
bmpWidth = head.biWidth;
bmpHeight = head.biHeight;
biBitCount = head.biBitCount;
int lineByte = (bmpWidth * biBitCount/8+3)/4*4;
if (biBitCount == 8)
{
pColorTable = new RGBQUAD[256];
fread(pColorTable, sizeof(RGBQUAD), 256, fp);
}
pBmpBuf = new unsigned char[lineByte * bmpHeight];
fread(pBmpBuf, 1, lineByte * bmpHeight, fp);
fclose(fp);
return 1;
}
bool saveBmp(char* bmpName, unsigned char* imgBuf, int width, int height,int biBitCount, RGBQUAD* pColorTable)
{
if (!imgBuf)
{
return 0;
}
int colorTablesize = 0;
if (biBitCount == 8)
{
colorTablesize = 768;
}
int lineByte = (width * biBitCount/8+3)/4*4;
FILE* fp = fopen(bmpName, "wb");
if (fp == 0) { return 0; }
BITMAPFILEHEADER fileHead;
fileHead.bfType = 0x4D42;
fileHead.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + colorTablesize + lineByte * height;
fileHead.bfReserved1 = 0;
fileHead.bfReserved2 = 0;
fileHead.bfOffBits = 54 + colorTablesize;
fwrite(&fileHead, sizeof(BITMAPFILEHEADER), 1, fp);
BITMAPINFOHEADER head;
head.biBitCount = biBitCount;
head.biClrImportant = 0;
head.biClrUsed = 0;
head.biCompression = 0;
head.biHeight = height;
head.biPlanes = 1;
head.biSize = 40;
head.biSizeImage = lineByte * height;
head.biWidth = width;
head.biXPelsPerMeter = 0;
head.biYPelsPerMeter = 0;
fwrite(&head, sizeof(BITMAPINFOHEADER), 1, fp);
if (biBitCount == 8)
{
fwrite(pColorTable, sizeof(RGBQUAD), 256, fp);
}
fwrite(imgBuf, height * lineByte, 1, fp);
fclose(fp);
return 1;
}
void main()
{
char readPath[]="C:\\Users\\123\\Desktop\\123.bmp";
readBmp(readPath);
cout<<"width="<<bmpWidth<<" "<<"height="<<bmpHeight <<" " << biBitCount;
char writePath[]="C:\\Users\\123\\Desktop\\1231.bmp";
saveBmp(writePath, pBmpBuf, bmpWidth, bmpHeight, biBitCount, pColorTable);
delete []pBmpBuf;
if(biBitCount==8)
delete []pColorTable;
}
运行结果如下: