Friday, September 14, 2012

Resize image Proportionally using javascipt

function reSizeImage (imgToResize,expWidth,expHeight) {

          
            var originalImg = new Image();
            originalImg = imgToResize;

            var originalWidth = originalImg.width;
            var originalHeight = originalImg.height;
           
            // Return image if fit with the existing div without resize       
            if (originalWidth <= expWidth && originalHeight <= expHeight)
            {
                return imgToResize;
            }
            // Resize image
            var newImgSize = setSizePresetImage(expWidth, expHeight, originalWidth, originalHeight);
           
            var newImg = new Image();
            newImg= originalImg;
            newImg.width=newImgSize.width;
            newImg.height=newImgSize.height;
            return newImg;
       
    };
    function setSizePresetImage (expW, expH, orgW, orgH) {
        //Get radio
        var ratio = orgH / orgW;

        if (orgW >= expW && ratio <= 1) {
            orgW = expW;
            orgH = orgW * ratio;
        }
        else if (orgH >= expH) {
            orgH = expH;
            orgW = orgH / ratio;
        }
        //return new width and height
        return ({"width":orgW, "height":orgH});
    }