#ifndef bmploader_hpp__ #define bmploader_hpp__ #include #include using namespace std; #include "FileIO.hpp" class BMPClass { private: union { short int si[2]; int i; char c[4]; }; int iHeight; int iWidth; int iSize; FileIO BMPFile; public: class BMPException { public: BMPException(const char *reason) : m_reason(reason) {} const char *reason() const { return m_reason; } private: const char *m_reason; }; char *cpData; void LoadBMP(char *cpAddress); void SaveBMP(char *cpAddress); int Width() const { return iWidth; } int Height() const { return iHeight; } int Size() const { return iHeight*iWidth*3; } }; void BMPClass::LoadBMP(char *cpAddress) { int iReadLoc; if (!BMPFile.OpenR(cpAddress)) throw BMPException("No such file"); BMPFile.Read(2,c,0); //Checks If file is BM if(si[0] != 19778) throw BMPException("File doesn't have BMP header"); BMPFile.Read(4,c,30); if (i) throw BMPException("File is compressed"); int bpp; BMPFile.Read(2,c,28); bpp = si[0]; if (bpp!=24 && bpp!=32) throw BMPException("Unsupported bit depth"); //Gets Width + Height BMPFile.Read(4,c,18); iWidth = i; BMPFile.Read(4,c,22); iHeight = i; //Gets Data starting location BMPFile.Read(4,c,10); iReadLoc = i; cpData = new char[iWidth*iHeight*3]; for (int y = 0; y < iHeight; ++y) { for (int x = 0; x < iWidth; ++x) { BMPFile.Read(3,c,iReadLoc); // BMP's are stored bottom-up so invert y-coordinate int iIndex = 3 * ((iHeight - y - 1) * iWidth + x); cpData[iIndex] = c[0]; cpData[iIndex+1] = c[1]; cpData[iIndex+2] = c[2]; if (bpp == 24) iReadLoc += 3; else iReadLoc += 4; } } BMPFile.Close(); } void BMPClass::SaveBMP(char *cpAddress) { if (!BMPFile.OpenW(cpAddress)) throw BMPException("Acces Denied"); //Writes all the BS before the file BMPFile.Write("BM",0,2); i = Size()+55; BMPFile.Write(c,2,4); i = 0; BMPFile.Write(c,6,4); i = 55; BMPFile.Write(c,10,4); i = 40; BMPFile.Write(c,14,4); i = Width(); BMPFile.Write(c,18,4); i = Height(); BMPFile.Write(c,22,4); si[0] = 1; si[1] = 8; BMPFile.Write(c,26,4); i=0; int iI = 0; while(iI < 6) { BMPFile.Write(c,30 + iI*4,4); iI++; } iI = 0; while(iI < Height()*Width()) { c[0]=cpData[iI*3]; c[1]=cpData[iI*3+1]; c[2]=cpData[iI*3+2]; c[3]=cpData[0]; BMPFile.Write(c,54+iI*4,4); iI++; } BMPFile.Close(); } #endif