Using Controls in the Microsoft Foundation Class Library - Image Handling
(Page 3 of 4 )
A picture is worth a thousand words is an ancient proverb. And this is true in modern programming also. Sometimes all you need is to take the next step and make it more stylish. Your application is a picture. A picture, I say! But how do we convince the application to show it?
You may think that this is quite an easy task because the anyway window draws everything as a picture and we can print ("draw") a text to the screen with a line and a TextOutW, function. However, an image is more complex than that. Achieving this task the traditional way is quite problematic.
But for our sake, using the GDI+ library can be done via some easy steps. If you're using an OS prior to XP or Windows 2003 Server Edition, you'll need a DLL file. You can download it from here. Hence, you shall see that after starting up the GDI+ it's child's play. First declare the stdafx.h in the library:
#include <gdiplus.h>
using namespace Gdiplus;
#pragma comment(lib, "gdiplus.lib")
Now we need to initialize the GDI+ resources. To do this, add (for us the CMFC_exampleApp) the following two variables as class members in the application file:
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
Continue adding in the Initistance of the same class the following line:
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
The GDI+ is already ready for use, but to complete the job, we add the ExitInstance() function from the override tab of the properties and insert this code snippet:
GdiplusShutdown(gdiplusToken);
Before we start, you should know what we'll make. Our goal is to open an image inside of our window. For this, we have to take an extra step in our file. Open up the properties tab and in the events section, find the ON_FILE_OPEN and add the COMMAND function. Here we overwrite the implemented file by opening and saving the path of the picture in the _fileName variable. Also we make sure that we can only open images that you can see in the szFilters string. Repeat the process to the OnFileNew, if you want to do the same when you create a new file.
void CMFC_exampleView::OnFileOpen()
{
TCHAR szFilters[] = _T("All Picture File(*.bmp,*.jpeg,*.jpg,*.gif,*.tiff)");
CFileDialog dlg(TRUE,_T(""), _T("*.*"),OFN_FILEMUSTEXIST,szFilters);
if (dlg.DoModal () == IDOK)
{
_fileName = dlg.GetPathName();
Invalidate();
}
else
return;
// TODO: Add your command handler code here
}
Next: Image Handling continued >>
More BrainDump Articles
More By Gabor Bernat