开发者

Resize image but keep its ratio - is it possible by means of HTML, CSS or jQuery?

Resize image but keep its ratio - is it possible by means of HTML, CSS or jQuery?

I have a top script displaying a list of users (will turn this script into a Drupal block later), with a link to their indi开发者_Go百科vidual profile web page. For the most of the users I have a foto in my database, which I'd love to display at the top page, but I don't know how to resize their fotos.

I.e. a user might have a 160x100 picture or a 20x40 picture, but on my top page I want the fotos to fit inside a 60x40 rectangle.

And I can't just write <img src="..." width="60" height="40"> because the images will appear distorted then (i.e. ratio won't be preserved).

Is there a way in HTML, CSS or jQuery to scale an image, but keep its ratio?

(And I don't want to download each image by a Perl/PHP-script, then run ImageMagick or anything similar - this is too heavy)


<img id="fixMe" src="something.jpg" />


jQuery(function(){
      var elm=jQuery('#fixMe');
      var allowedHeight=40;
      var allowedWidth=60;
      var ratio= allowedHeight/allowedWidth;
      var width=elm.width();
      var height=elm.height();
      if(width>height)
      {
        elm.width(allowedWidth);
        elm.Height(width*(allowedHeight/allowedWidth));
      }
      else      
    {
       elm.height(allowedHeight);
        elm.width(height*(allowedWidth/allowedHeight));
    }
});


You can use the jQuery image resize library, and called it like:

$(function() {
  $( ".resizeme" ).aeImageResize({ height: 200, width: 250 });
  // Works with one parameter as well
  $( ".resizeme" ).aeImageResize({ width: 250 });
});


I think this is the wrong approach. Your comments on the other answers suggest that you aren't limiting the filesize/dimensions of uploaded photos. As you are expecting to resize the image client-side, the full image is fetched by the browser for each user in your top list.

What happens if someone uploads a 500KB jpeg? It's a possibility, a desktop-sized image at 100% quality could easily be that big. If you're showing 10 users, this could make each page view 5MB. I've seen plenty of sites go over bandwidth (and therefore be unavailable) due to serving original images.

What's your reason for not using a server-side resizer, such as timthumb?


If you set either the width or the height and leave the other one blank, it will resize and keep the ratio for you.

To do the clipping, maybe stick the IMG inside a DIV with dimensions of 60x40 and set overflow: hidden.


Since you don't know if your picture is always too wide or too tall, this alone will not solve your problem, but you can always just set either width or height and your browser should scale the other dimension accordingly (preserving aspect ratio)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜