I think your math is not right here. If the input image was twice the height of the screen but only half the width of the screen, this code would not work.

See the createThumbnailFromElement() function in apps/gallery/js/MetadataParser.js for an example. If you assume the video argument is false and the rotation argument is 0, then this function is a lot like your scaleImage() function.  I think lines 40 to 51 of that file are the most important.