Charles Yeung
Charles Yeung

Reputation: 38795

jQuery/PHP - Resize an image with direct proportion

Hi
Suppose I have several image with different width and height, I want all of them to fit in the img tag with 200 width and 200 height and direct proportion(image won't be distortion).

How can I do it in PHP or Jquery?

Thanks

Upvotes: 0

Views: 672

Answers (3)

Matt Ball
Matt Ball

Reputation: 359966

var max = 200;
$('img').each(function ()
{
    var $this = $(this);
    if ($this.height() > $this.width())
    {
        $this.height(max);
    }
    else
    {
        $this.width(max);
    }
});

http://jsfiddle.net/mattball/qtVkT/

Upvotes: 1

user578895
user578895

Reputation:

This will constrain all images with class 'image' to be <= 200x200px

If you want it to be in a perfect 200x200 box, wrap it in a 200x200px div

$('.image').each(function(){
   var $this = $(this);
   $this[$this.width() > $this.height() ? 'width' : 'height'](200);
});

Upvotes: 1

fabrik
fabrik

Reputation: 14365

From this tutorial:

  • We assume the thumbnail should be 100 pixels, either wide or high.
  • We load the original image, and check its dimensions.
  • If the picture is higher than wide, we set the height of the thumb to 100 pixels.
  • The width of the thumbnail is the original width multiplied with 100 pixels divided by its height.
  • Thumbnail height = original width * (100 / original height)
  • This way we preserve the original aspect ratio.
  • If the original picture is wider than high, we do the same to the height of the thumbnail.
  • If they are the same, we simply create a 100x100 pixels image.

IMO resizing images with jQuery is a bad practice, i advise you shouldn't do that if you can use GD library.

Upvotes: 0

Related Questions