Saturday, May 26, 2007

Extracting Single Images from a CImageList object in MFC

Here is the function:

It takes 3 parameters, and returns nothing.

  • lstImages: A pointer to the CImageList object containing all of the images.
  • nImage: The index of the image that is going to be extracted.
  • destBitmap: A pointer to the CBitmap object that is going to contain the extracted image.

The function makes a copy of the image list, and moves the requested image to the front of that list.

It then draws the requested image into the destination bitmap.

void CMyWindowClass::GetImageFromList(CImageList *lstImages,
int nImage, CBitmap* destBitmap)
//First we want to create a temporary image list we can manipulate
CImageList tmpList;

//Then swap the requested image to the first spot in the list
tmpList.Copy( 0, nImage, ILCF_SWAP );

//Now we need to get som information about the image
IMAGEINFO lastImage;

//Heres where it gets fun
//Create a Compatible Device Context using
//the valid DC of your calling window
CDC dcMem; dcMem.CreateCompatibleDC (GetWindowDC());

//This rect simply stored the size of the image we need
CRect rect (lastImage.rcImage);

//Using the bitmap passed in, Create a bitmap
//compatible with the window DC
//We also know that the bitmap needs to be a certain size.
destBitmap->CreateCompatibleBitmap (this->GetWindowDC(),
rect.Width (), rect.Height ());

//Select the new destination bitmap into the DC we created above
CBitmap* pBmpOld = dcMem.SelectObject (destBitmap);

//This call apparently "draws" the bitmap from the list,
//onto the new destination bitmap
tmpList.DrawIndirect (&dcMem, 0, CPoint (0, 0),
CSize (rect.Width (), rect.Height ()), CPoint (0, 0));

//cleanup by reselecting the old bitmap object into the DC
dcMem.SelectObject (pBmpOld);

It looks big, but remove the comments and you have a mere 12 lines of code.

you can call the function above use two lines of code like following:

CBitmap bitMap;

GetImageFromList(&m_ImageListSrc, extractIndex, &bitMap);

Then you can do what you like with the variable bitMap;

The original URL of the solution is:

No comments: