Friday, September 17, 2010

Resizing image size at runtime in a SharePoint web part to a constant size

If you have an column in any of the web parts and the url of the control is set dynamically by the user, then obviously, we do not have a control as to how the image appears based on the size resolution. If you take a look at the profile image, MySite displays, you know what I am talking about. Irrespective of the size of the image that user upload, MySite always shows the same image size.

If you want the same functionality, the following code helps.

Step 1: Write the following JavaScript in any master page you have access to. Alternatively, you could write these functions in a .js file and have a link to the Master page.

function imgResizeMaxHW(obj, maxwidth, maxheight) {
    /*var obj = document.getElementById(objid); */
    var oldResize = obj.onresize;
    obj.onresize = null;
    if ((obj != null) && (obj.height > 0) && (obj.width > 0)) {
        try {
            var ratiomax = maxheight / maxwidth;
            var ratioobj = obj.height / obj.width;

            if (ratiomax > ratioobj) { // too wide
                if (obj.width > maxwidth)
                    obj.width = maxwidth;
            }
            else { // too tall
                if (obj.height > maxheight)
                    obj.height = maxheight;
            }

            imgUndoTrSize(objid);
        }
        catch (e) {
        }
    }
    obj.onresize = oldResize;
}

function imgResizeMax(obj, max) {
    imgResizeMaxHW(obj, max, max);
}

function imgUndoTrSize(objid) {
    if (objid == null)
        return;

    var obj = document.getElementById(objid + '_TR');

    if (obj != null) {
        obj.height = null;
    }
}
function imgUndoSize(objid) {
    imgUndoTrSize(objid);
    imgResizeTbl(objid);
}

function imgResizeTbl(imgid) {
    if (imgid == null)
        return;

    var img = document.getElementById(imgid);
    var tbl = document.getElementById('table' + imgid);
    if (tbl != null && img != null) {
        try {
            tbl.width = img.width;
        }
        catch (e) { }
    }
}

Step 2: Wherever you have the <img> element in HTML, we just need to write the following piece of code to it so that one of the above Java functions is called on "onload" event of the control.

onload="imgResizeMaxHW(this, 200, 200)"

We are saying in the above code that, any time image is bigger than 200,200 in size, maximum size of the image displayed is 200*200.

Hope this helps!!!

No comments:

Post a Comment