33

jQuery Image Resize

Posted by Eric Juden on Jul 08, 2009

Let me start off by saying, I LOVE jQuery! It’s the greatest thing since sliced bread! Now that I have that out of the way, I’ve been working on developing some WordPress themes for work. We are going to be launching a blogs site (using WordPress MU) fairly soon for faculty, staff, and eventually students. So, in the process we are building a blog that will be used as an online newsletter. On the blog page, they want the top story to take precedence, and for the image to be larger. So to accomplish this, I wanted to scale down the other images and keep the aspect ratio. Enter jQuery…

I was looking out there at some of the solutions already completed. I didn’t see anything that quite did what I was looking for. So I made my own function:

$(document).ready(function() {
    $('.story-small img').each(function() {
        var maxWidth = 100; // Max width for the image
        var maxHeight = 100;    // Max height for the image
        var ratio = 0;  // Used for aspect ratio
        var width = $(this).width();    // Current image width
        var height = $(this).height();  // Current image height
 
        // Check if the current width is larger than the max
        if(width > maxWidth){
            ratio = maxWidth / width;   // get ratio for scaling image
            $(this).css("width", maxWidth); // Set new width
            $(this).css("height", height * ratio);  // Scale height based on ratio
            height = height * ratio;    // Reset height to match scaled image
            width = width * ratio;    // Reset width to match scaled image
        }
 
        // Check if current height is larger than max
        if(height > maxHeight){
            ratio = maxHeight / height; // get ratio for scaling image
            $(this).css("height", maxHeight);   // Set new height
            $(this).css("width", width * ratio);    // Scale width based on ratio
            width = width * ratio;    // Reset width to match scaled image
        }
    });
});

The 2nd line of code says to grab every image with a class of ‘story-small’. The block for the height is just a safety net. I have it there in case the height is still larger than the max. There are a hundred ways to skin a cat, so I’m sure there are plenty of other ways to do this.

Bookmark and Share

Comments

  • Mikko says:

    You probably should set width in first if-statement like you do with height:

    width = maxWidth;

    Otherwise it calculates new width wrong in second if.

  • Eric Juden says:

    Thanks Mikko, I overlooked that. :)

  • Takitani says:

    Very good, thx for sharing

  • Thanks – totally bailed me out!

  • khan says:

    You are just modifying the image properties. Can someone tell me if I can actually do some image manipulation on the client side (JQuery) before it gets uploaded to the server?

    Say someone is uploading 2MB 2500×2500 image, I want to resize it to 500×500 and then send the modified (smaller) file to the server rather than full 2MB? Or it is too much to ask from javascript?

  • Eric Juden says:

    khan,

    I think you’d be better off using a server-side language like php or asp.net to process the images when the files are being uploaded.

    Eric

  • sylbal says:

    Hi,

    I start from this post to create a resize image function but I have problem with safari,
    var width = $(this).width(); // Current image width
    var height = $(this).height(); // Current image height

    returns 0

    I try to find a work around then keep you posted

  • Cedric says:

    Hi,

    I’m sorry to be so bad but this is not working for me.

    I’ve downloaded jquery 1.3.2 on jquery.com

    I insert it like that

    script src=”jquery-1.3.2.js” type=”text/javascript”

    I paste your code exactly in my page.

    I have only that:

    img src=”dff30__N1D0212.JPG” class=”story-small”

    and nothing has changed.

    Can you please help me. I need so baddly this to work.

    Thanks

    Cedric

  • Eric Juden says:

    Cedric,

    Can you send a link to the page you are doing this on? Do you have a javascript debugger that is showing any errors?

    Thanks,

    Eric

  • Cedric says:

    Hi,

    thnaks for your quick answer

    http://em-bassadors.com/mini/

    Thank you.

    Cedric
    cedric.massonnat@gmail.com

  • Eric Juden says:

    Cedric,

    Try putting your image inside a div with a class of “story-small”. The css was looking for an element with a class of “story-small” with an image inside of it.

    Eric

  • Cedric says:

    Thank you so much !!
    I don’t know why I put a class inside the img.

    Thanks.

    BTW, you have a very nice blog, very interesting.

    Take care

  • Thanks a lot! this script is lake Druce Lee, simple and effective.

  • Michael says:

    Hey Eric,

    i have a question to your Script.

    Am i right, that this script only changes the size of the div and doesnt resize the picture itself?

    Greetings,
    Michael

  • Eric Juden says:

    Michael,

    You are not correct. The script is resizing the image, and not a div. The 2nd line of the script says (‘.story-small img’). That is grabbing any image tag inside of a div with a class of story-small.

    Thanks,

    Eric

  • Michael says:

    Ah nice thanks for the Information, now i know how to use it.

    Greetings,
    Michael

  • Jules Van de Velde says:

    To select any img with a class of story-small you could use (‘img.story-small’) if you didn’t want to put each image inside of a div

  • joren says:

    Hi,

    This is a very handy script, but I’m having some problems with it.
    I’m browsing with Safari, Chrome and Firefox on a mac and the first time I visit a page on my website the images arn’t resized. If I reload the page, they resize.

    I think my browser doesn’t know the size of the images when the document is loaded.

    this is an example of my website I’m developing:
    http://fileflambe.be/topics/117-raad-de-screenshot-game-editie?page=7

    Is there a solution for this problem?

  • Eric Juden says:

    Joren,

    When I view the link you posted it shows the images full size until the page is done loading. Then the image is scaled down. I’m not sure how to fix this besides making your page load faster so it’s not as noticeable.

    Thanks,

    Eric

  • Jared says:

    Or try preloading the image….

  • joren says:

    weird,

    I have the same problem on this page
    http://fileflambe.be/posts/1798-google-auto-aanvullen
    the first time the image stay big.

    If it is only me who is seeing them big, there is noproblem :)

  • Eric Juden says:

    Joren,

    I think you’d probably be better of doing this on the server side, instead of using Javascript. Your images are pretty large and it’s taking the page longer to load.

    Eric

  • Geeo says:

    you are wrong, jquery does not get the image width, instead of “each()” use “load()”; try an alert imediatly after you get the image height in both each and load events, you will see that “each” returns width 0 and “load” returns the correct width :)

  • James says:

    Hi Eric
    Thanks for this!
    I think I have solved Joren’s problem, which I was also experiencing, by doing this:

    $(‘.main_content_text img’).load(function() {
    $(‘.main_content_text img’).each(function() {

    at the start instead of:

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

    What do you think?

    Thanks, James

  • keyur says:

    simillar problem as weird, but in IE thier is no issue. it may cause problem in FF

  • Worked right away, thanks!

  • Dave Reeder says:

    It doesn’t work in Google Chrome as it tries to execute your code at the same time as loading the images, so we need to tell it to wait for the images to load (so wrap this function round your $(‘.images img’).each function):

    $(‘.images img’).load(function() {
    // your code in here
    });

  • Eric Juden says:

    Dave,

    Thanks for the input. When I used this I didn’t have super large images loading. I meant it more as an image resize for small to medium size images.

    Eric

  • steven lots says:

    You can solve the problems with safari and chrome, by running the code on $(window).load(…) instead of $(document).ready(….).

  • Vyom says:

    Hi Mikko

    The script is very good. But i have some problem.
    What you script did, only set the width & height right?

    But when i right click on image & save as, that case originla image is save.

    I want resize that to save new image.

    Please help me if you know?
    Thank you
    Vyom

  • D123 says:

    Hello,

    The script is very helpfull.
    Runs perfect in FF,Safari,Chrome.
    Doesn’t work in IE.
    Please help me.

    Thank you,
    D

Spam Protection by WP-SpamFree