数字图像处理学习笔记(1.0)---位图的读写、几何变换、傅里叶变换、直方图均衡

位图的读写


#include"bmp.h"
#include<iostream>
#include<cstring>
#include<cstdio>

using namespace std;


Bitmap::Bitmap()
{

}

Bitmap::~Bitmap()
{
	if (dataBuf!=NULL)
		delete[] dataBuf;
	dataBuf = NULL;
	if (colorTable != NULL)
		delete[] colorTable;
	colorTable = NULL;
}

bool Bitmap::read(char* fileName)
{
	FILE* f = fopen(fileName, "rb");
	if (f == NULL)
		return false;

	if (dataBuf != NULL)//释放旧的图像数据内存和颜色表内存
		delete[] dataBuf;
	if (colorTable != NULL)
		delete[] colorTable;
	dataBuf = NULL;
	colorTable = NULL;
	
	fread(&fileHeader, sizeof(BITMAPFILEHEADER), 1, f);
	fread(&infoHeader, sizeof(BITMAPINFOHEADER), 1, f);

	width_p = infoHeader.biWidth;
	height_p = infoHeader.biHeight;
	bitCount = infoHeader.biBitCount;

	if (bitCount == 8)
	{
		colorTable = new RGBQUAD[256];
		fread(colorTable, sizeof(RGBQUAD), 256, f);
	}

	dataBuf = new unsigned char[infoHeader.biSizeImage];
	fread(dataBuf, 1, infoHeader.biSizeImage, f);

	fclose(f);
	return 1;
}

bool Bitmap::write(char* fileName)
{
	FILE* f = fopen(fileName, "wb");
	if (f == NULL)
		return false;

	int colorTableSize = 0;
	if (bitCount == 8)
		colorTableSize = sizeof(RGBQUAD)* 256;

	int headerSize = sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+colorTableSize;
	int lineSize = (width_p*bitCount / 8 + 3) / 4 * 4;
	int dataSize = lineSize*height_p;

	fileHeader.bfType = 0x4D42;
	fileHeader.bfSize = headerSize + dataSize;
	fileHeader.bfReserved1 = 0;
	fileHeader.bfOffBits = headerSize;

	infoHeader.biSize = 40;
	infoHeader.biWidth = width_p;
	infoHeader.biHeight = height_p;
	infoHeader.biPlanes = 1;
	infoHeader.biBitCount = bitCount;
	infoHeader.biCompression = BI_RGB;
	infoHeader.biSizeImage = dataSize;
	infoHeader.biXPelsPerMeter = 0;
	infoHeader.biYPelsPerMeter = 0;
	infoHeader.biClrUsed = 0;
	infoHeader.biClrImportant = 0;

	fwrite(&fileHeader, sizeof(BITMAPFILEHEADER), 1, f);
	fwrite(&infoHeader, sizeof(BITMAPINFOHEADER), 1, f);
	if (bitCount == 8)
	{
		fwrite(colorTable, sizeof(RGBQUAD), 256, f);
	}
	fwrite(dataBuf, 1, dataSize, f);

	fclose(f);
	return true;
}

测试:

#include"bmp.h"
#include<iostream>

using namespace std;

int main()
{
	char* fileName = "qianxun.bmp";
	Bitmap* bmp = new Bitmap();
	bmp->read(fileName);
	bmp->write("write.bmp");
	delete bmp;
	return 1;
}




posted @ 2014-12-31 21:28  corfox  阅读(243)  评论(0编辑  收藏  举报