jQuery/PHP - Resize an image with direct proportion
Hi
Suppose I have seve开发者_如何学运维ral 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
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/
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);
});
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.
精彩评论