1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
|
#include "Bitmap.hpp"
Bitmap::Bitmap()
: m_hBitmap(NULL), m_iWidth(0), m_iHeight(0)
{ }
// create a bitmap from a file
Bitmap::Bitmap(HDC hDC, LPCTSTR szFileName)
: m_hBitmap(NULL), m_iWidth(0), m_iHeight(0)
{
Create(hDC, szFileName);
}
Bitmap::~Bitmap()
{
Free();
}
void Bitmap::Free()
{
// delete the bitmap graphics object
if (m_hBitmap != NULL)
{
DeleteObject(m_hBitmap);
m_hBitmap = NULL;
}
}
BOOL Bitmap::Create(HDC hDC, LPCTSTR szFileName)
{
// free any previous bitmap info
Free();
// open the bitmap file
HANDLE hFile = CreateFile(szFileName, GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return FALSE;
}
// read the bitmap file header
BITMAPFILEHEADER bmfHeader;
DWORD dwBytesRead;
BOOL bOK = ReadFile(hFile, &bmfHeader, sizeof(BITMAPFILEHEADER),
&dwBytesRead, NULL);
if ((!bOK) || (dwBytesRead != sizeof(BITMAPFILEHEADER)) || (bmfHeader.bfType != 0x4D42))
{
CloseHandle(hFile);
return FALSE;
}
BITMAPINFO* pBitmapInfo = (BITMAPINFO*) (new BITMAPINFO_256);
if (pBitmapInfo != NULL)
{
// read the bitmap info header
bOK = ReadFile(hFile, pBitmapInfo, sizeof(BITMAPINFOHEADER), &dwBytesRead, NULL);
if ((!bOK) || (dwBytesRead != sizeof(BITMAPINFOHEADER)))
{
CloseHandle(hFile);
Free();
return FALSE;
}
// store the width and height of the bitmap
m_iWidth = (int) pBitmapInfo->bmiHeader.biWidth;
m_iHeight = (int) pBitmapInfo->bmiHeader.biHeight;
// skip (forward or backward) to the color info, if necessary
if (pBitmapInfo->bmiHeader.biSize != sizeof(BITMAPINFOHEADER))
{
SetFilePointer(hFile, pBitmapInfo->bmiHeader.biSize - sizeof(BITMAPINFOHEADER), NULL, FILE_CURRENT);
}
// read the color info
bOK = ReadFile(hFile, pBitmapInfo->bmiColors, pBitmapInfo->bmiHeader.biClrUsed * sizeof(RGBQUAD),
&dwBytesRead, NULL);
// get a handle to the bitmap and copy the image bits
PBYTE pBitmapBits;
m_hBitmap = CreateDIBSection(hDC, pBitmapInfo, DIB_RGB_COLORS, (PVOID*) &pBitmapBits, NULL, 0);
if ((m_hBitmap != NULL) && (pBitmapBits != NULL))
{
SetFilePointer(hFile, bmfHeader.bfOffBits, NULL, FILE_BEGIN);
bOK = ReadFile(hFile, pBitmapBits, pBitmapInfo->bmiHeader.biSizeImage, &dwBytesRead, NULL);
if (bOK)
{
return TRUE;
}
}
}
// something went wrong, so cleanup everything
Free();
return FALSE;
}
| |