C++读取BMP文件
#include <string> #include <vector> #include <fstream> using namespace std; class CBitmap { public: typedef unsigned char BYTE; typedef unsigned short WORD; typedef unsigned long DWORD; typedef long LONG; typedef struct{ DWORD bfSize; // file size WORD bfReserved1; WORD bfReserved2; DWORD bfOffBits; // offset from file header to pixel data }BITMAPFILEHEADER; typedef struct{ DWORD biSize; // structure size LONG biWidth; LONG biHeight; WORD biPlanes; // must be 1 WORD biBitCount; // bit number of one pixel DWORD biCompression; DWORD biSizeImage; LONG biXPelsPerMeter; LONG biYPelsPerMeter; DWORD biClrUsed; DWORD biClrImportant; }BITMAPINFOHEADER; CBitmap(){} ~CBitmap(){} bool load(const string& file) { ifstream fs(file, ios_base::in | ios_base::beg | ios_base::binary); if (!fs.is_open()){ return false; } fs.read((char*)&m_tag, sizeof(WORD)); if (m_tag != 0x4D42){ return false; } fs.read((char*)&m_fileHeader, sizeof(m_fileHeader)); if (fs.gcount() != sizeof(m_fileHeader)){ return false; } fs.read((char*)&m_infoHeader, sizeof(m_infoHeader)); if (fs.gcount() != sizeof(m_infoHeader)){ return false; } m_palette.resize(m_fileHeader.bfOffBits - sizeof(m_tag)-sizeof(m_fileHeader)-sizeof(m_infoHeader)); fs.read((char*)&m_palette[0], m_palette.size()); m_data.resize(m_fileHeader.bfSize - m_fileHeader.bfOffBits); fs.read((char*)&m_data[0], m_data.size()); if (fs.gcount() != m_data.size()){ return false; } fs.close(); return true; } bool save(const string& file) { ofstream fs(file, ios_base::binary); if (!fs.is_open()){ return false; } fs.write((char*)&m_tag, sizeof(WORD)); fs.write((char*)&m_fileHeader, sizeof(m_fileHeader)); fs.write((char*)&m_infoHeader, sizeof(m_infoHeader)); fs.write((char*)&m_palette[0], m_palette.size()); fs.write((char*)&m_data[0], m_data.size()); fs.close(); return true; } WORD m_tag; BITMAPFILEHEADER m_fileHeader; BITMAPINFOHEADER m_infoHeader; vector<BYTE> m_palette; vector<BYTE> m_data; };