bmp图片的有关操作
读取bmp图片 并生成新的bmp图片
#include "stdafx.h"
#include <windows.h>
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
long bfSize, bfOffBits;
long biWidth, biHeight, biBitCount, biSizeImage;
// 打开待读的位图文件
FILE *fp = NULL;
int ret = fopen_s(&fp, "D:\\VC\\BMP\\img1024.bmp", "rb");
if (fp == 0) {
cout << "open file failed" << endl;
return -1;
}
// 建立待生成的位图文件
FILE *wfp = NULL;
ret = fopen_s(&wfp, "D:\\VC\\BMP\\img_out.bmp", "wb");
if (wfp == 0) {
cout << "create output file failed" << endl;
return -1;
}
// 获取BITMAPFILEHEADER
BITMAPFILEHEADER fileheader = { 0 };
fread(&fileheader, sizeof(BITMAPFILEHEADER), 1, fp);
if (fileheader.bfType != 0x4D42) {
cout << "Not BMP Image" << endl;
return -1;
}
else {
bfSize = fileheader.bfSize;
bfOffBits = fileheader.bfOffBits;
fwrite(&fileheader, sizeof(BITMAPFILEHEADER), 1, wfp); // 写入BITMAPFILEHEADER
}
// 获取BITMAPINFOHEADER
BITMAPINFOHEADER head = { 0 };
fread(&head, sizeof(BITMAPINFOHEADER), 1, fp);
biWidth = head.biWidth;
biHeight = head.biHeight;
biBitCount = head.biBitCount;
biSizeImage = head.biSizeImage;
if (biBitCount != 24) {
fclose(fp);
cout << "Not 24bit Bitmap" << endl;
return -1;
}
else {
fwrite(&head, sizeof(BITMAPINFOHEADER), 1, wfp); // 写入BITMAPINFOHEADER
}
// 输出文件属性信息
cout << "文件大小 => " << bfSize << "Byte" << endl;
cout << "数据区偏移量 => " << bfOffBits << "Byte" << endl;
cout << "宽度 => " << biWidth << "px" << endl;
cout << "高度 => " << biHeight << "px" << endl;
cout << "颜色位数 => " << biBitCount << "bit" << endl;
cout << "数据区大小 => " << biSizeImage << "Byte" << endl;
// 把位图数据区读入BYTE缓冲区
BYTE *pBmpBuf = new BYTE[biSizeImage];
size_t size = 0;
while (true) {
int iret = fread(&pBmpBuf[size], 1, 1, fp);
if (iret == 0) {
break;
}
else {
size = size + iret;
}
}
fclose(fp);
int pitch = biWidth % 4; // 每行数据字节数必须是4的倍数
BYTE ar[1]={0};//不足4的倍数补0
BYTE vRGB[3];
for (int i =0; i <biHeight; ++i)
{
int realPitch = i*pitch;
for (int j = 0; j < biWidth; ++j)
{
vRGB[0] = pBmpBuf[(i*biWidth + j) * 3 + realPitch]; // BLUE
vRGB[1] = pBmpBuf[(i*biWidth + j) * 3 + 1 +realPitch]; // GREEN
vRGB[2] = pBmpBuf[(i*biWidth + j) * 3 + 2 + realPitch]; // RED
fwrite(vRGB, sizeof(vRGB), 1, wfp); //把描述一个像素的R、G、B值写入输出缓冲区
}
for(int m=0;m<pitch;m++)
fwrite(ar,sizeof(ar),1,wfp); //补零
}
// 关闭文件缓冲区
delete[] pBmpBuf;
pBmpBuf = NULL;
// 写输出图像
fclose(wfp);
cout << endl << "创建输出文件成功" << endl;
return 0;
}