Link to home
Start Free TrialLog in
Avatar of jxbma
jxbmaFlag for United States of America

asked on

Whats the best way to scale a windows bitmap?

I'm working with a windows C++ app and need to apply scaling to a bitmap image which is loaded in memory.
(Windows BITMAP)

What is the best way to scale a bitmap image?
I have a windows BITMAP which I want to apply scaling to.

I do have access to the boost and opencv libraries as part of this project.

Thanks,
JohnB
Avatar of Zoppo
Zoppo
Flag of Germany image

Hi jxbma,

a common and easy way to do this is to create another in-memory bitmap of the wanted (scaled) size and draw the original bitmap into the new one using ::StretchBlt. To do so both bitmaps need to be selected into memory device contexts. Here's some (untested) code how this could look like:
// obtain a display DC to use as base for the memory DCs
HDC hdcScreen = ::CreateDC( "DISPLAY", NULL, NULL, NULL );

// prepare source memory DC and select the source bitmap into it
HDC hdcSource = ::CreateCompatibleDC( hdcScreen );
SIZE sSource = /*the size of the source bitmap*/
HBITMAP hBmpSource = /*the source bitmap*/;
HBITMAP hBmpOldSource = (HBITMAP)::SelectObject( hdcSource, hBmpSource );

// prepare destination memory DC, create and select the destination bitmap into it
HDC hdcDest = ::CreateCompatibleDC( hdcScreen );
SIZE sDest = /*the wanted size of the scaled target bitmap*/
HBITMAP hBmpDest = ::CreateCompatibleBitmap( hdcSource, sDest.cx, sDest.cy );
HBITMAP hBmpOldDest = (HBITMAP)::SelectObject( hdcDest, hBmpDest );

// set halft-ton stretch-blit mode for better scaling quality
::SetStretchBltMode( hdcDest, HALFTONE );

// draw the bitmap scaled into the destination memory DC
::StretchBlt( hdcDest, 0, 0, sDest.cx, sDest.cy, hdcSource, 0, 0, sSource.cx, sSource.cy, SRCCOPY );

// release everything
::SelectObject( hdcSource, hBmpOldSource );
::SelectObject( hdcDest, hBmpOldDest );
::DeleteDC( hdcSource );
::DeleteDC( hdcDest );
::DeleteDC( hdcScreen );

// now you should have the scaled bitmap in 'hBmpDest'
...

Open in new window

It might be you're not satisfied with the quality of the scaled bitmap - if so you should consider doing similar things using GDI+, compard with GDI it has improved drawing and smoothing/antialiasing functionality.

Hope that helps,

ZOPPO
Avatar of jxbma

ASKER

Zoppo:

Thanks for the feedback.

Our app does image analysis. Client apps will pass us either an HBMP or LPBITMAP.
The analysis is part of a library (which will eventually get wrapped).
We don't have access to HDC's from within the library.

Is there another way to try to scale the bitmap through the windows API, or through openCv?

Thanks,
JB
ASKER CERTIFIED SOLUTION
Avatar of Zoppo
Zoppo
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial