Function to dynamically resize images using jQuery

flattr this!

UPDATE: I have created a jQuery plugin that dynamically resizes the images. It is faster and is optimized better (minified).

I have noticed that there has been quite a bit of interest in my post about dynamically resizing images using jQuery. I have created a function to do this job better. Not only it makes the code cleaner but it also makes it a lot easier to use it.

First, for those people looking for a quick lookup of solution, here is the optimized version of the function followed by a couple of examples to use it:

$.fn.resize=function(a){var d=Math.ceil;if(a==null)a=200;var e=a,f=a;$(this).each(function(){var b=$(this).height(),c=$(this).width();if(b>c)f=d(c/b*a);else e=d(b/c*a);$(this).css({height:e,width:f})})};

$("img").resize(200);
$("#thumbs img").resize(150);

And now the explanation.. The function takes one argument, a number, which is the maximum height and/or the width of the image. The function automatically decides what is the best way to resize the image as its all calculated from the proportions of the original image.

What follows below is an expanded (non-optimized) version of the function and explanation on what each statement does:

NOTE: I do highly recommend using the optimized version of the function above

$.fn.resize = function(max_size) {
m = Math.ceil;
if (max_size == undefined) {
max_size = 200;
}
h=w= max_size;
$(this).each(function() {
image_h = $(this).height();
image_w = $(this).width();
if (image_h > image_w) {
w = m(image_w / image_h * max_size);
} else {
h = m(image_h / image_w * max_size);
}
$(this).css({height:h,width:w});
})
};

Line 1 declares the function “resize” and accepts a variable for maximum height/width.
Line 2 stores the Math.ceil function to a single letter variable for calling up later by m(). It is same as calling Math.ceil() and is done this way for reducing the size of the script (called minifying).
Lines 3 to 5 check if a maximum height/width was specified, if not, the script defaults to a maximum size of 200px.
Line 6 sets two variables ‘h’ for height and ‘w’ for width to the maximum size. One of these variables will be changed depending up the proportions of the image being resized.
Line 7 starts the jQuery.each function that iterates over each image one by one.
Line 8 stores the image’s height to a variable and is for reducing the size of the script.
Line 9 stores the image’s width to a variable and is for reducing the size of the script.
Line 10 checks if the image height is greater than the image width.
Line 11 only executes when the image’s height is bigger than the width. It calculates the image’s new width with proportion to its original size (which would be less than the height).
Line 12 is basic else statement.
Line 13 only executes when the image’s width is bigger than the height. It calculates the image’s new height with proportion it its original size (which would be less than the width).
Line 15 uses the jQuery’s built-in CSS function to set the new height and width for the image.

  • Anon

    Looks great. I have one question. When the page first loads, the images are full size and snap to the smaller “resized” size after about 1 second. What can i do so the end user never see’s the original size?

    Thanks

  • Anon

    I forgot to mention that this only happens in IE

    • http://adeelejaz.com Adeel

      Can you please tell me which version of IE is the culprit? I thought I fixed that bugger!

  • Anon

    This is in IE 8 and in emulation IE 7 mode. Doesnt seem to happen in Firefox.

    Thanks again for helping me with this issue.

  • Anon

    I say emulate but i mean compatibility mode IE 7.

    • http://adeelejaz.com Adeel

      I have updated the function above with some improvements for Internet Explorer. I do not know how many images you are trying to resize but there is quite a bit of history of Internet Explorer and slow JavaScript.

      There are ways use can help IE execute JavaScript faster. Make sure the resize function is added in the head with the jQuery load function.

      One more thing which helps in this case is improving the selectors. Instead of using something generic like $(“img”), try experimenting with introducing an id around the images that are being resized, for example $(“#gallery img”).

      If the problem persists, please point to the document so I can have a look.

  • Anon

    Still didnt work. In fact, the images werent resizing right compared to your older code i got on the previous article. I cant link to the page because its on a dev site.

    Thanks anyways

  • Magdy

    Hi Adeel!
    Thanks for this nice work!
    Very, very, very useful jquery script!
    It helps me a lot!!

    But I have an issue… The height of the images are not resizing accordingly to the script.
    For example for images with the height > width, image resize correctly on the width.
    But for images with the height < width, they don't get resized on height, they still get resized on the width only…

    Hope you can help me!
    Yanks

    • http://adeelejaz.com Adeel

      Hi,

      Sorry for the delay with reply.. the server had been acting weird so I had to do a refresh.. and thanks for bringing the issue to my notice.. I’m going to put a new post soon (in a day or two) with the fix.. Just subscribe to make sure you get the update.

      Thanks

    • http://adeelejaz.com Adeel

      Hi Magdy,

      Just wanted to let you know you can get the updated version now from: http://adeelejaz.com/blog/jquery-re-size-plugin-dynamically-resize-images/

  • D123

    Hello,

    Fantastic script.
    works perfect in FF,safari,chrome.
    doesnt work in IE7.

    Please help me.

    Thnx,
    D

  • muzzoman

    Thank you very much!
    I just needed a simple func to create thumbnails “on the fly”, yours feels my needs very well.
    You made me earn the time to write a function by myself.
    Greetings from Italy
    (I’ll try new version as well, for IE compatibility)

  • Evan

    this is great. I am a new programmer doing a project for class and found this code. its my first jquery.

    is there any way to get it to work with an image that you are referencing via a url and not an image that is on your server?

    Thanks,
    Evan

  • http://kali-dasan.blogspot.com kalidasan

    This is doing great. but some time, images width & height set to zero. So its not visible at that time.

  • Igal

    Hello, Adeel!
    First of all thank you for your plugin! Great job!
    I’ve been trying to implement it on my page with some dynamically loaded images and got some awkward result.
    This is how it looks before I apply your plugin, it resized hardcore, with width=’220′ height=’220′:
    http://i44.tinypic.com/168x7i9.jpg
    It’s aligned with css, and beside the fact that the images are not proportionally resized it looks nice. But here’s the result when I tried to implement the plugin:
    http://i39.tinypic.com/154k2eq.jpg

    This is the code that loads the images and implements the resize:
    $(function(){
    $.getJSON(“inc/API.php”, {command:”top3″}, function(result) {
    for(var i = 0; i<result.length; i++) {
    $("“).appendTo(“#top3″);
    $(“#top3 img”).aeImageResize({ height: 220, width: 220 });
    } Shadowbox.init({
    continuous:true,
    displayCounter:false,
    overlayColor:”#a09e92″,
    overlayOpacity:0.8
    });
    });
    });

    This is the HTML:

    And the CSS:
    #divContent
    {
    width:860px;
    border: 1px solid;
    border-color: #dbd9ca;
    border-radius: 10px;
    -moz-border-radius: 10px;
    margin:5px;
    margin-top:20px;
    margin-bottom:20px;
    padding:5px;
    clear:both;
    margin-bottom:20px;
    }

    #top3
    {
    width:850;
    /*margin:50px auto;*/
    text-align:center;
    vertical-align:middle;
    position:relative;
    }

    img#top3img
    {
    border-radius: 10px;
    -moz-border-radius: 10px;
    margin-left:13px;
    margin-right:20px;
    margin-top:17px;
    }

    Any idea why it happens and how to fix it?

    Thank you!

    • http://adeelejaz.com/ Adeel Ejaz

      You need to put wrap the images with a block element and set a height and width of 220px on it. Something like this: http://jsfiddle.net/CbdyY/

  • Neutron

    Hi Adeel, can I ask whether this would work with a CMS such as indexhibit? I am not a coder so don’t partiulalry understand how this works! Thanks for any help.

    • http://adeelejaz.com/ Adeel Ejaz

      What you are looking at is a really old version. Please grab the latest version from here: http://adeelejaz.com/blog/type/jquery-image-resize-plugin/

      It should, in theory, work with anything including CMS. There are two steps, first one is to include the plugin’s file (jquery.ae.image.resize.min.js) in the

      
      

      and then use jQuery to pass the images you want resized to the plugin. There is an demo bundled in with the zip.

  • Neutron

    Ah right, thanks very much Adeel. I know a little about using plugins with a CMS already so I’ll give this a shot.

    One other thing, here’s an example of what I’m trying to achieve: http://www.serlinassociates.com/

    All the images resize by jquery

  • Ardi

    IE sux, to fix IE problem… just put the loader in your page, so the image will not show until it all finish loading…

  • Kamil Tamiola

    Fantastic! Work!

  • ujj

    fantastic piece of work!!! thanks for this

  • Sam Mittelstaedt

    I’m attempting to use this in conjunction with a Skitter slide show and Joomla/MooTools. Other extensions require “jQuery.noConflict();”
    Resizing works IF I disable the noconflict() call. Is anyone running this on a site that includes MooTools+jQuery.noconflict?