11.04.2014 Views

Advanced MFC Programming

Advanced MFC Programming

Advanced MFC Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 10. Bitmap<br />

CGDIDoc::CGDIDoc()<br />

{<br />

m_hDIB=NULL;<br />

}<br />

We will allocate global memory each time a new bitmap file is opened. So when the application exits,<br />

we need to check variable m_hDIB to see if the memory has been allocated. If so, we need to release it:<br />

CGDIDoc::~CGDIDoc()<br />

{<br />

if(m_hDIB != NULL)<br />

{<br />

::GlobalFree(m_hDIB);<br />

m_hDIB=NULL;<br />

}<br />

}<br />

We need to modify function CGDIDoc::Serialize(…) to load data from DIB file. First, when a file is<br />

being opened, variable m_hDIB may be currently in use. In this case, we need to release the global memory:<br />

void CGDIDoc::Serialize(CArchive& ar)<br />

{<br />

if(ar.IsStoring())<br />

{<br />

}<br />

else<br />

{<br />

BITMAPFILEHEADER bf;<br />

DWORD dwSize;<br />

LPSTR lpDIB;<br />

……<br />

if(m_hDIB != NULL)<br />

{<br />

::GlobalFree(m_hDIB);<br />

m_hDIB=NULL;<br />

}<br />

Reading data from a DIB file needs the following steps:<br />

1) Read bitmap file header.<br />

1) Verify that the the file format is correct.<br />

1) From the bitmap file header, calculate the total memory needed, then allocate enough buffers.<br />

1) Read the DIB data into the allocated buffers.<br />

We can call CArchive::Read(…) to read bytes from the file into the memory. In the sample, first<br />

bitmap file header (data contained in structure BITMAPFILEHEADER) is read:<br />

……<br />

……<br />

if<br />

(<br />

ar.Read<br />

(<br />

(LPSTR)&bf,<br />

sizeof(BITMAPFILEHEADER)<br />

) != sizeof(BITMAPFILEHEADER)<br />

)return;<br />

Then the file type is checked. If it is DIB format, global memory is allocated, which will be used to<br />

store DIB data:<br />

……<br />

if(bf.bfType != 'MB')return;<br />

294

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!