How to load a bitmap from bmp file and draw it in DC?

There are two main steps:

  • Load the bitmap from the file to a memory DC.
  • Paint the content of the memory DC to the one which display the bitmap.

In MFC, there is no API to load a bitmap directly from a file, but you can use a Win32 API: LoadImage.
Here is the delaration of LoadImage.


HANDLE LoadImage(
HINSTANCE hinst, //handle to instance, if load from file, it should be NULL
LPCTSTR lpszName, //image resource name or the image file path
UINT uType, //image type
//1. IMAGE_BITMAP
//2. IMAGE_CURSOR
//3. IMAGE_ICON
int cxDesired, //desired width
int cyDesired, //desired height
UINT fuLoad //load options
);

After this,  the following steps are similar with loading a bitmap from resource. Here is a short example.



CClientDC dc(this);
CDC *mdc=new CDC;
mdc->CreateCompatibleDC(&dc);

CBitmap bitmap;
//CBitmap is devived from CGdiObject
//It has a handle:m_hObject, which can obtained with LoadImage
bitmap.m_hObject=(HBITMAP)::LoadImage(
NULL,
“b1.bmp”,
IMAGE_BITMAP,
500,
400,
LR_LOADFROMFILE);

mdc->SelectObject(bitmap);
CRect rect;
GetClientRect(&rect);
//BitBlt()
dc.BitBlt(0,0,rect.right,rect.bottom,mdc,0,0,SRCCOPY);

//release mdc
delete mdc;

Tags: , , ,