wxHaskell: Scaling a Bitmap Image

I ran into this page while trying to figure out how to scale a bitmap image from within wxHaskell. The solution posted by the OP there scales the drawing context (e.g., the canvas) and not the bitmap itself.

To scale the bitmap itself, just do it like this:

import Graphics.UI.WX
import Graphics.UI.WXCore

scaleBitmap ... = do
    imgScaled <- imageConvertToBitmap =<< imageScale img (sz newWidth newHeight)
    -- do stuff with imgScaled; e.g., draw it somewhere with drawBitmap
    bitmapDelete imgScaled
    where
        img = image "foo.bmp"
        newWidth = 100
        newHeight = 20

The key is to load up the bitmap with the generic image function, and not the usual bitmap function. This way, you can make use of the imageScale function to scale your image, and then you can convert it back again to bitmap format with imageConvertToBitmap. Finally, when we are done with drawing this image somewhere, we free the memory used up to create the bitmap version of it, by calling bitmapDelete. A bit clunky, but simple enough. I tested it with a Windows BMP with an alpha channel and it worked quite nicely.

By the way, wxHaskell is very easy to learn — you just need to skim Daan Leijen’s paper whenever you get stuck. (Leijen also wrote the beautifully powerful Parsec library — another library I enjoyed using once I got the hang of it.)

Advertisements