Resize images using jQuery

26 Comments

UPDATE: I have created a plugin that dynamically resizes the images using jQuery. It basically does the same job but is really easy to use and is optimized better (minified).

Recently I needed a script to resize images on the page. I did not want to lose the actual resolution but just wanted to create thumbnails on the go.

I spent some time searching but could not find anything suitable. The options I found were just too much while I needed something simple. At the end, I ended up writing some own code (I’m a coder after all :P ).
var max_size = 200;
$("img").each(function(i) {
if ($(this).height() > $(this).width()) {
var h = max_size;
var w = Math.ceil($(this).width() / $(this).height() * max_size);
} else {
var w = max_size;
var h = Math.ceil($(this).height() / $(this).width() * max_size);
}
$(this).css({ height: h, width: w });
});

The script resizes the images without distorting the proportions. First of all, a variable is declared called max_size that is set to the maximum height or width that the picture needs to be resized to. Then using jQuery we match all img elements and using the each function, we go through each one of them resizing them as necessary. The if statement checks which side of the image needs to be kept to the maximum and the other one is calculated proportionally.

In the final line, the new height and width values are assigned using CSS. Neat eh ;)

26 Comments (+add yours?)

  1. Kashif
    Aug 16, 2009 @ 19:58:38

    lalalala
    I already did this a few years back for my homepage :P
    Remember The Dark Side? :P
    just didnt link it up with CSS :O

    Reply

  2. Adeel
    Aug 16, 2009 @ 21:44:54

    Look at the code carefully.. it ain’t any usual JavaScript .. its jQuery ;)

    Reply

  3. Anon
    Nov 03, 2009 @ 14:37:00

    I wanted to say thanks for writing this little script. It took me a long time to find something that works and it appears to be rather simple to implement.

    Thanks!

    Reply

  4. Adeel
    Nov 08, 2009 @ 03:33:37

    I have seen a lot of interest in this article so I have created a function which is far easier and better to use than this. Check it out at: Function to dynamically resize images using jQuery

    Reply

  5. Stupor
    Dec 06, 2010 @ 09:13:26

    Hello!
    Well, I had the same problem: I wanted to resize images that exceed a certain width. And I also wrote some javascript on my own. However, while this code works perfect on Internet Explorer and Firefox, it refuses to do on Chrome. Maybe anyone can help me?

    Here’s my code:

    $(document).ready(function(){
    $(‘#wrap img’).each(function(){

    var pixw=$(this).attr(‘width’);
    var pixh=$(this).attr(‘height’);

    //This alert window was just used for a test…
    alert(pixw +” x “+ pixh);

    if(pixw>490)
    {
    $(this).attr(‘width’,490);
    }
    });
    });

    BTW: While on IE and FF the alert window shows the correct extensions of the images, Chrome always shows “0 x 0″, so not even the detection worked here… That’s somewhat frustrating… (#wrap is the surrounding container that includes many further containers).

    Reply

    • Adeel Ejaz
      Dec 07, 2010 @ 00:35:07

      You haven’t submitted your HTML code so it is difficult to see. Why I recommend is you download the plugin and use the following code to run it:

      $(function() {
        $( "#wrap img" ).aeImageResize({ width: 490 });
      });

      The reason I recommend using the plugin is because Chrome doesn’t resize proportionally if the height and the width attributes are present. Moreover, the CSS height and width declarations can also have an effect. The jQuery Resize Plugin handles all these cases.

      Reply

    • Adeel Ejaz
      Dec 07, 2010 @ 00:36:47

      And you can download the latest version of the jQuery Image Resize plugin from here: http://adeelejaz.com/blog/type/jquery-image-resize-plugin/

      Reply

  6. Stupor
    Dec 07, 2010 @ 06:05:56

    Hey Adeel!

    Thanx for your reply! Actually, I already tried out your jQuery plugin – works perfect, even on Chrome ;)
    However, I think I gonna dive deeper into my code as well soon, just to find the reason why Chrome is so reluctant to do what I wanted it to do… But your plugin will be my first choice so far. Thank you again for your support!

    Reply

  7. Rama Mohan
    Dec 24, 2010 @ 10:21:11

    Thank you very much. This is a very usefull script

    Reply

  8. Mike
    Dec 24, 2010 @ 17:21:09

    Great, thanks, looks very useful!

    Reply

  9. emrecamasuvi
    Jan 19, 2011 @ 14:22:29

    it worked for me! such a nice snippet, thanks mate.

    Reply

  10. Andy Feliciotti
    Mar 04, 2011 @ 14:48:15

    Awesome tip, thanks!

    Reply

  11. Ton
    Jun 22, 2011 @ 15:51:22

    Hey man!

    Thanks for the script..It works like a charm.. :)

    Reply

  12. sushie
    Oct 05, 2011 @ 16:58:02

    thanks for the script, still works fine!

    i modified it a little, so u can define max H & max W and resize the image proportional, maybe usefull to someone else:

    ——
    var max_w=500;
    var max_h=250;
    $(“img”).each(function(i) {
    var this_w=$(this).height();
    var this_h=$(this).width();
    if (this_w/this_h < max_w/max_h) {
    var h = max_h;
    var w = Math.ceil(max_h/this_h * this_w);
    } else {
    var w = max_w;
    var h = Math.ceil(max_w/this_w * this_h);
    }
    $(this).css({ height: h, width: w });
    });
    ——

    *cheers

    Reply

  13. Cale
    Oct 09, 2011 @ 09:07:52

    Merci beaucoup pour le script !

    Reply

  14. Hova
    Nov 05, 2011 @ 10:22:14

    Nice! Your script has come to good use!

    Reply

  15. Christian
    Jan 23, 2012 @ 23:04:47

    Just in case anyone else is still using this script instead of the plugin, it works better if you wait until each image has loaded fully.

    Instead of:
    $(“img”).each(function(i) {
    use:
    $(“img”).load(function() {

    Reply

  16. Md. Rasel Ahmed
    Mar 08, 2012 @ 06:19:49

    Really so helpful . I can successfully use this

    Reply

  17. Craig
    Mar 21, 2012 @ 15:49:00

    What is the purpose of this script? The image “size” is still the same. Wouldn’t it be easier to just add a width and height attribute instead of using a script?

    Thanks,
    Craig

    Reply

    • Adeel Ejaz
      Mar 21, 2012 @ 16:00:36

      The purpose of this script is to resize images of different sizes to a bounding size. For example, you have space of 200px by 200px but your images are oddly sized, i.e. 500px x 750px, 450px x 300px. This script resizes the images to fit in the dimensions given without distorting the images.

      Of course, no one is stopping you from “manually” calculating the aspect ratio for each image and then setting the desired height and width in HTML. Its good for one or two images but if you have lots of images, specially being uploading by users in all shapes and sizes, some programmers like to automate things :)

      Reply

  18. Regis
    Mar 30, 2012 @ 22:31:48

    You know you no longer need any javascript for this any longer. Maybe three years ago before max/min CSS attributes were available, but it’s simply CSS now:

    img {width:auto; height:auto; max-width:200px; max-height:200px;}

    Reply

    • Adeel Ejaz
      Mar 31, 2012 @ 00:34:24

      If I remember correctly IE6 didn’t support max-width and it was buggy in IE8. It breaks for IE8 breaks you are using XHTML doctype.

      Reply

      • rgthree
        Mar 31, 2012 @ 01:53:10

        Yup, IE6 doesn’t work with max/min width/height. Do people still pretend that IE6 matters? Haha. You might be right about IE8.. not sure. Caniuse.com doesn’t mention anything like that.

        Anyway, one enhancement you can make (if you weren’t going to opt for the CSS route to avoid the overhead of scanning the DOM for all images and then calculating each’s new dimensions) would be to use naturalWidth/Height if available, otherwise use the current width/height. This ensures you’re using the actual ratio of the image, instead of the current in the DOM, which may have been fiddled with via CSS:

        var max_size = 200;
        $(“img”).each(function(i) {
        var w,h;
        w = this.naturalWidth || $(this).width();
        h = this.naturalHeight || $(this).height();
        if (h > w) {
        $(this).css({ height: max_size, width: Math.ceil(w / h * max_size) });
        } else {
        $(this).css({ height: Math.ceil(h / w * max_size), width: max_size });
        }
        });

        Reply

  19. JR Galia
    May 18, 2012 @ 00:17:38

    this is great. thanks for the code.

    Reply

Leave a Reply