Resize images using jQuery

flattr this!

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 ;)

  • http://www.xtasee.com.pk Kashif

    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

  • http://adeelejaz.com Adeel

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

    • http://www.hetal.avayainfoways.com/ Hetal

      right Adeel ! !!!!!!!!!!

  • Anon

    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!

  • Pingback: Function to dynamically resize images using jQuery

  • http://adeelejaz.com Adeel

    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

  • Stupor

    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).

    • http://adeelejaz.com/ Adeel Ejaz

      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.

    • http://adeelejaz.com/ Adeel Ejaz

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

  • Stupor

    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!

  • http://lifestyle-india.blogspot.com Rama Mohan

    Thank you very much. This is a very usefull script

  • http://www.myinsults.com Mike

    Great, thanks, looks very useful!

  • http://camasuvi.net emrecamasuvi

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

  • http://drawne.com Andy Feliciotti

    Awesome tip, thanks!

  • http://www.tonsantos.com Ton

    Hey man!

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

  • sushie

    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

    • http://adeelejaz.com/ Adeel Ejaz

      This post is really old. I’ve made a plugin of this that works in all the browsers: jQuery Image Resize Plugin

    • http://twitter.com/geedmo Geedmo

      Excellent code! thanks for the scripts.. it was really useful for me and works really fine !

      I made a simplified version if you’re interested… is the same but I just want to share with you.. :)

       containerwd and  containerhg are the size of the, div, span.. who determines the size where the image is wrapped 

      $(“img”).each(function(i) {
      imghg = ((naturalimgwd/ naturalimghg < containerwd / containerhg) ? 
                   containerhg : 
                   Math.ceil(containerwd/naturalimgwd * naturalimghg)); 

      imgwd = ((f.o.naturalimgwd/f.o.naturalimghg < containerwd/containerhg) ? 
                   Math.ceil(containerhg/naturalimghg * naturalimgwd) :
                   containerwd);

      $(this).css({ height:
      imghg
      , width:
      imgwd
      });});

  • Cale

    Merci beaucoup pour le script !

  • Hova

    Nice! Your script has come to good use!

  • Christian

    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() {

  • http://www.skybazar.com Md. Rasel Ahmed

    Really so helpful . I can successfully use this

  • Craig

    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

    • http://adeelejaz.com/ Adeel Ejaz

      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 :)

  • http://regisgaughan.com Regis

    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;}

    • http://adeelejaz.com/ Adeel Ejaz

      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.

      • http://regisgaughan.com rgthree

        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 });
        }
        });

  • http://jrgalia.com JR Galia

    this is great. thanks for the code.

  • http://www.hetal.avayainfoways.com/ Hetal

    Thnks bro

  • http://www.hetal.avayainfoways.com/ Hetal

    it doesnt work in 100% width

    I want this one in center any way

    Please reply me

    • http://adeelejaz.com/ Adeel Ejaz

      Can you please create an example using jsfiddle.net? Just to give me an idea what you are trying to do.

  • Enrique

    hi! I create a jQuery plugin with your code https://github.com/CKGrafico/jQuery_Resize I write your url in the README.txt
    Thank you!!

  • http://www.facebook.com/mulli.bahr מולי באהר

    Nice job.
    Clearly you can generalize the concept by applying different types of manipulations, such as:
    1. rounded corners
    2. alpha effect
    3. wrap with a link
    4. set ALT / Title
    etc…

    • http://adeelejaz.com/ Adeel Ejaz

      Don’t understand what you mean. I’m guessing you can use CSS for rounded corners, etc.

    • Trixit

       you are so lazy…

  • http://www.facebook.com/leonardo.sariego Leonardo Sariego

    This is awesome! Works like a charm. Thanks a lot

  • http://profile.yahoo.com/PB2GIUVJAQ7TLYNSRZI66FMXRU mantre_h

    thanks for the scripts..