How to display part of an image for the specific width and height?
        Posted  
        
            by 
                Brady Chu
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Brady Chu
        
        
        
        Published on 2013-11-13T03:31:20Z
        Indexed on 
            2013/11/13
            3:53 UTC
        
        
        Read the original article
        Hit count: 400
        
Recently I participated in a web project which has a huge large of images to handle and display on web page, we know that the width and height of images end users uploaded cannot be control easily and then they are hard to display. At first, I attempted to zoom in/out the images to rearch an appropriate presentation, and I made it, but my boss is still not satisfied with my solution, the following is my way:
var autoResizeImage = function(maxWidth, maxHeight, objImg) {
    var img = new Image();
    img.src = objImg.src;
    img.onload = function() {
        var hRatio;
        var wRatio;
        var Ratio = 1;
        var w = img.width;
        var h = img.height;
        wRatio = maxWidth / w;
        hRatio = maxHeight / h;
        if (maxWidth == 0 && maxHeight == 0) {
            Ratio = 1;
        } else if (maxWidth == 0) {
            if (hRatio < 1) {
                Ratio = hRatio;
            }
        } else if (maxHeight == 0) {
            if (wRatio < 1) {
                Ratio = wRatio;
            }
        } else if (wRatio < 1 || hRatio < 1) {
            Ratio = (wRatio <= hRatio ? wRatio : hRatio);
        }
        if (Ratio < 1) {
            w = w * Ratio;
            h = h * Ratio;
        }
        w = w <= 0 ? 250 : w;
        h = h <= 0 ? 370 : h;
        objImg.height = h;
        objImg.width = w;
    };
};
This way is only intended to limit the max width and height for the image so that every image in album still has different width and height which are still very urgly.
And right at this minute, I know we can create a DIV and use the image as its background image, this way is too complicated and not direct I don't want to take. So I's wondering whether there is a better way to display images with the fixed width and height without presentation distortion?
Thanks.
© Stack Overflow or respective owner