1

I'm trying to build a script that browser-resizes images that are larger than the container:

  $('img').each(function(i){
    var parent_width = parseInt($(this).parent().width()),
        image_width = parseInt($(this).width());

    if(parent_width !== image_width){
      $(this).width(parent_width).wrap(
         '<a class="resized-image" href="' + this.src + '">'
       + ' <span class="msg">'
       + '   This image has been resized to ' + parent_width + ' pixels'
       + '   and ' + $(this).height() + ' pixels'
       + '</span>'
       + '</a>'
      );
    }
  });

The resizing works, but how can I get a nice message there telling the user the original image size, percentage to which the image was resized and the original image size in KB?

Like

This image has been resized to 400 x 300 (50%). Original image has 800 x 600 and 75 KB. Click to view the original

So far I could only figure out the width of the resized image (the height() returns 0 for some reason)

Alex
  • 66,732
  • 177
  • 439
  • 641
  • 2
    The filesize is irrelevant and useless information. Unless a thumbnail script was used, the image has already been downloaded, so if I click to view the fullsize then it will just come from cache instantly. – Niet the Dark Absol May 03 '12 at 14:00
  • yes, they both have the same file size because they are the same image, but still I'd like to display this information in the ribbon above the image... – Alex May 03 '12 at 14:01
  • 2
    There's an easy way to resize in CSS: `img { max-width: 100%; }` Of course, you don't get your clickable links that way. – Blazemonger May 03 '12 at 14:03
  • See [this question](http://stackoverflow.com/q/3877027/901048) for tips about this problem. You can't measure the dimensions of an image until it's fully `.load`ed (that's why you're getting the `height()` as zero), but you can't detect when it's `.load`ed if it's cached without a little additional trickery. – Blazemonger May 03 '12 at 14:05

2 Answers2

1

Wrap your code with $(window).load

$(window).load(function() {
     // your code
});
jfrm
  • 86
  • 3
1

Try this:

$('img').one('load', function () {

    var parent_width = parseInt($(this).parent().width()),
        image_width = parseInt($(this).width());

    if(parent_width !== image_width){
      $(this).width(parent_width).wrap(
         '<a class="resized-image" href="' + this.src + '">'
       + ' <span class="msg">'
       + '   This image has been resized to ' + parent_width + ' pixels'
       + '   and ' + $(this).height() + ' pixels'
       + '</span>'
       + '</a>'
      );
    } 

});

$('img').each(function () {
     //If image is cached by browsers, trigger .load()
    if (this.complete){        
         $(this).trigger('load');
    }
 });
​

Test in jsfiddler.

Kibria
  • 1,865
  • 1
  • 15
  • 17