codea teams

Image Resize With jQuery

Thank you to Kyle Solomon for providing this code snippet. www.jetchicken.com

This resize function is used when images need to be resized on the fly as a page is loaded to accommodate desired layout. The function automatically caches image as well so they appear in all browsers at page load without requiring refresh. The function assumes image element is hidden (display:none) until after resizing is complete to preserve desired page presentation.

Applications are photo galleries, or placing images uploaded by user (mized sizes) in standardized display widths and heights. Loop through gallery images calling this function each iteration while passing img identifyer.

//params:   i = jquery identifyer ('#imgid');  mH = max resize height;  mW = max resize width

function resize(i,mH,mW) {                       
    var iS = $(i).attr('src');
    var tI = new Image();
    tI.onload = function() {
        // always called upon setting image source (last line of code triggers)
        var w = tI.width;
        var h = tI.height;
        // can increase scale percentages for finer scale granularity with tradeoff of 
        // higher client-side overhead
        var scl_h = 0.96;
        var scl_w = 0.96;
        while (w>mW || h>mH) { w=w*scl_w; h=h*scl_h; }
        var nH = parseInt(h) + 'px';
        var nW = parseInt(w) + 'px';
        // fade in image after resize complete
    tI.src = iS;