使用GetHBITMAP()和MFC CStatic :: SetBitmap()可能发生内存泄漏

时间:2011-12-13 12:33:01

标签: c++ mfc gdi+

我每隔100ms调用以下函数。它的目标是从 renderBuffer 中获取图像,调整其大小并使用 SetBitmap()在对话框的CStatic控件中显示它。 问题是,当执行此函数时,我每秒都会观察到相当大的内存使用量。它在CStatis控件中显示调整大小的图像没有问题,但我在任务管理器中看到每个第二个进程分配额外的4兆字节的内存,并且在进程耗尽内存之前不会停止。

以下是代码,如果您知道可能存在什么问题,请告诉我。

void CAppDlg::UpdatePreview( const RenderBuffer* renderBuffer )
{
HBITMAP hbmReturn = NULL; 
Gdiplus::Bitmap  *bmPhoto  = NULL;
Gdiplus::Bitmap bmPhoto( THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT );
CBitmap Bmp1;

Gdiplus::Bitmap image( 780, 780, 4*780, PixelFormat32bppARGB, renderBuffer->buffer );

int sourceWidth  = image.GetWidth();
int sourceHeight = image.GetHeight();

int destX = 0,
    destY = 0; 

float nPercent  = 0;
float nPercentW = ((float)THUMBNAIL_WIDTH/(float)sourceWidth);;
float nPercentH = ((float)THUMBNAIL_HEIGHT/(float)sourceHeight);

if(nPercentH < nPercentW)
{
    nPercent = nPercentH;
    destX    = (int)((THUMBNAIL_WIDTH - (sourceWidth * nPercent))/2);
}
else
{
    nPercent = nPercentW;
    destY    = (int)((THUMBNAIL_HEIGHT - (sourceHeight * nPercent))/2);
}

int destWidth  = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);

bmPhoto.SetResolution( image.GetHorizontalResolution(), image.GetVerticalResolution() );

Gdiplus::Graphics *grPhoto = Gdiplus::Graphics::FromImage( &bmPhoto );
Gdiplus::Color colorW(255, 255, 255, 255);
grPhoto->Clear( colorW );
grPhoto->SetInterpolationMode( Gdiplus::InterpolationModeHighQualityBicubic );
grPhoto->DrawImage( &image, Gdiplus::Rect(destX, destY, destWidth, destHeight) );

bmPhoto.GetHBITMAP( colorW, &hbmReturn );

m_BitmapPreview.SetBitmap( hbmReturn ); // ---- without this line memory usage doesn't go up rapidly every second.

DeleteObject( hbmReturn ); // ---- returns non-zero which would point out that it was freed properly.
delete grPhoto;
}

感谢您的帮助!

问候。

1 个答案:

答案 0 :(得分:0)

我猜你应该使用DeleteObject

以下是我认为代码的外观:

// ..............
bmPhoto.GetHBITMAP( colorW, &hbmReturn );

HBITMAP prev = m_BitmapPreview.SetBitmap( hbmReturn ); // ---- without this line memory usage doesn't go up rapidly every second.
if (NULL != prev)
{
   DeleteObject(prev); // *** do not forget to delete the previously associated bitmap
}

DeleteObject( hbmReturn ); // ---- returns non-zero which would point out that it was freed properly.
// .........