Friday, May 7, 2010

Resize Image with javascript

function resizeImageByWidth(img,MaxWidth) {
    try {
        if (img != null && img.src != "") {
            img.attributes.removeNamedItem("width");
            img.attributes.removeNamedItem("height");

            var oW = img.width;
            var oH = img.height;

            if (oW > MaxWidth) {
                var rW = parseFloat(oW) / parseFloat(MaxWidth);
                img.width = parseInt(oW / rW);
                img.height = parseInt(oH / rW);
            }
        }
    }
    catch (ex) {
        img.width = MaxWidth;
    }
}

function resizeImage(img, maxHeight, MaxWidth) {
    try {
        if (img != null && img.src != "") {
            img.attributes.removeNamedItem("width");
            img.attributes.removeNamedItem("height");

            var oW = img.width;
            var oH = img.height;

            if (oW > MaxWidth || oH > maxHeight) {
                var rW = parseFloat(oW) / parseFloat(MaxWidth);
                var rH = parseFloat(oH) / parseFloat(maxHeight);
                var ratio = Math.max(rW, rH);
                img.width = parseInt(oW / ratio);
                img.height = parseInt(oH / ratio);
            }
        }
    }
    catch (ex) {
        img.height = maxHeight;
        img.width = MaxWidth;
    }
}
To use in the image just add onload event event on image


any size is given automatically removed.

No comments:

Post a Comment