Imagem de redimensionamento Jquery

Gostaria de começar uma discussão sobre o redimensionamento da imagem usando jQuery.

Essa é a minha contribuição, mas acho que estou longe da solução. E os recortes? Quem me pode ajudar?

$(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
    }

    // 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
    }
});

});

Author: tvanfosson, 2009-07-17

14 answers

Tem de recalcular a largura e a altura após a primeira condição. Aqui está o código de script inteiro:

$(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
    }

    var width = $(this).width();    // Current image width
    var height = $(this).height();  // Current image height

    // 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
    }
});
 26
Author: Aleksandar Janković, 2010-11-01 15:50:29

Algumas sugestões:

  • Faça disto uma função em que possa passar num tamanho máximo ou mínimo, em vez de codificá-lo com codificação; isso irá torná-lo mais reutilizável {[[7]}
  • se usar o método de jQuery {[[0]}, como .animate({width: maxWidth}), ele deverá escalar a outra dimensão para si automaticamente.
 10
Author: Nathan Long, 2009-07-17 14:15:24
Bom Começo. Eis o que descobri:
$('img.resize').each(function(){
    $(this).load(function(){
        var maxWidth = $(this).width(); // Max width for the image
        var maxHeight = $(this).height();   // Max height for the image
        $(this).css("width", "auto").css("height", "auto"); // Remove existing CSS
        $(this).removeAttr("width").removeAttr("height"); // Remove HTML attributes
        var width = $(this).width();    // Current image width
        var height = $(this).height();  // Current image height

        if(width > height) {
            // Check if the current width is larger than the max
            if(width > maxWidth){
                var 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
            }
        } else {
            // Check if current height is larger than max
            if(height > maxHeight){
                var 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
            }
        }
    });
});

Isto tem o benefício de lhe permitir especificar a largura e a altura, permitindo que a imagem continue a escalar proporcionalmente.

 6
Author: Tyler, 2012-01-31 22:57:43
Olha para o Jcrop. Eu uso-o e é muito bom.

Http://deepliquid.com/content/Jcrop.html

 5
Author: FWH, 2009-07-17 14:09:47
$(function() {
  $('.mhz-news-img img').each(function() {
    var maxWidth = 320; // Max width for the image
    var maxHeight = 200;    // Max height for the image
    var maxratio=maxHeight/maxWidth;
    var width = $(this).width();    // Current image width
    var height = $(this).height();  // Current image height
    var curentratio=height/width;
    // Check if the current width is larger than the max

    if(curentratio>maxratio)
    {
        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
    }
    else
    { 
        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
    }
  });
});
 5
Author: Miehz, 2012-07-17 19:30:45
$(document).ready(function(){
    $('img').each(function(){
        var maxWidth = 660;
        var ratio = 0;
        var img = $(this);

        if(img.width() > maxWidth){
            ratio = img.height() / img.width();
            img.attr('width', maxWidth);
            img.attr('height', (maxWidth*ratio));   
        }
    });
});
Isso vai fazer o truque de magia para todos que usam o mais recente jquery. Certifique-se que configura o seu selector à direita (eu usei $('img'), mas isso pode ser diferente no seu caso). Isto só funciona para o modo paisagem. Mas se você olhar para ele, apenas algumas coisas têm que ser feitas para configurá-lo como retrato, aka, se img.altura () > altura máxima) material
 3
Author: ThomasV, 2012-02-13 22:52:58
$(function() {
    $('.story-small img').each(function() {
        var maxWidth = 100; // Max width for the image
        var maxHeight = 100;    // Max height for the image
        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>height && 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
        }
        else if(height>width && 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
        }
    });
});
 2
Author: Osman, 2011-03-12 18:11:09

CSS:

.imgMaxWidth {
    max-width:100px;
    height:auto;
}
.imgMaxHeight {
    max-height:100px;
    width:auto;
}

HTML:

<img src="image.jpg" class="imageToResize imgMaxHeight" />

JQuery:

<script type="text/javascript">
function onLoadF() {
    $('.imageToResize').each(function() {
        var imgWidth = $(this).width();
        if (imgWidth>100) {
            $(this).removeClass("imgMaxHeight").addClass("imgMaxWidth");
        }
    });
}
window.onload = onLoadF;
</script>
 1
Author: user3841678, 2014-07-15 16:51:30

Você pode redimensionar a imagem com este pedaço de código

    var maxWidth = 600;
    $("img").each(function () {
      var imageWidth = $(this).width();
      var imageHeight = $(this).height();
        if (imageWidth > maxWidth) {
          var percentdiff = (imageWidth - maxWidth) / imageWidth * 100;
          $(this).width(maxWidth);
          $(this).height(imageHeight - (imageHeight * percentdiff / 100));
        }
   });
 1
Author: Zeeshan Mahboob, 2017-01-16 12:25:04
Modificando a resposta de Aleksandar para torná-la um plugin jquery e aceita maxwidth e maxheight como argumentos, sugerido por Nathan.
$.fn.resize = function(maxWidth,maxHeight) {
return this.each(function() {
    var ratio = 0;
    var width = $(this).width();
    var height = $(this).height();
    if(width > maxWidth){
        ratio = maxWidth / width;
        $(this).css("width", maxWidth);
        $(this).css("height", height * ratio);
        height = height * ratio;
    }
    var width = $(this).width();
    var height = $(this).height();
    if(height > maxHeight){
        ratio = maxHeight / height;
        $(this).css("height", maxHeight);
        $(this).css("width", width * ratio);
        width = width * ratio;
    }
});
};

Utilizado como $('.imgClass').resize(300,50);

 0
Author: Ahamed, 2013-10-23 12:29:23
function resize() {resizeFrame(elemento, margin);};

jQuery.event.add(window, "load", resize);
jQuery.event.add(window, "resize", resize);
function resizeFrame(item, marge) {
  $(item).each(function() {
  var m = marge*2;
  var mw = $(window).width()-m; 
  var mh = $(window).height()-m;
  var w = $('img',this).width();
  var h = $('img',this).height();
  var mr = mh/mw;
  var cr = h/w;
  $('img',this).css({position:'absolute',minWidth:(w-w)+20,minHeight:(h-h)+20,margin:'auto',top:'0',right:'0',bottom:'0',left:'0',padding:marge});
    if(cr < mr){
        var r = mw/w;
        $('img',this).css({width: mw});
        $('img',this).css({height: h*r});
    }else if(cr > mr){
        var r = mh/h;
        $('img',this).css({height: mh});
        $('img',this).css({width: w*r});
    }
  });  
}
 0
Author: GMartins, 2013-12-03 18:20:27

E o antigo posto... um pouco quieto. Redimensionar é uma coisa, mas pode deixar imagens redimensionadas sem filtro, e parecer um pouco desorganizado. Então eu adicionei algumas linhas ao post original para adicionar uma margem esquerda para centralizar quaisquer imagens redimensionadas.

$(".schs_bonsai_image_slider_image").each(function()
{
    var maxWidth = 787; // Max width for the image
    var maxHeight = 480;    // 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
        height = height * ratio;    // Reset height to match scaled image
    }
    var newwidth = $(this).width();
    var parentwidth=$(this).parent().width();
    var widthdiff=(parentwidth-newwidth)/2;
    $(this).css("margin-left",widthdiff);
});
 0
Author: Gavin Simpson, 2015-03-01 00:31:25
Há tanto código aqui, mas acho que esta é a melhor resposta.
function resize() {
            var input = $("#picture");
            var maxWidth = 300;
            var maxHeight = 300;
            var width = input.width();
            var height = input.height();
            var ratioX = (maxWidth / width);
            var ratioY = (maxHeight / height);
            var ratio = Math.min(ratioX, ratioY);

            var newWidth  = (width * ratio);
            var newHeight = (height * ratio);
            input.css("width", newWidth);
            input.css("height", newHeight);
};
 0
Author: Tomás Escamez, 2015-03-31 11:56:25

ImgLiquid (um 'Plugin' do jQuery) parece fazer o que você pedir.

Demonstração:
http://goo.gl/Wk8bU

Exemplo JsFiddle:
http://jsfiddle.net/karacas/3CRx7/#base

Javascript

$(function() {

    $(".imgLiquidFill").imgLiquid({
        fill: true,
        horizontalAlign: "center",
        verticalAlign: "top"
    });

    $(".imgLiquidNoFill").imgLiquid({
        fill: false,
        horizontalAlign: "center",
        verticalAlign: "50%"
    });
     });

Html

<div class="boxSep" >
    <div class="imgLiquidNoFill imgLiquid" style="width:250px; height:250px;">
        <img alt="" src="http://www.juegostoystory.net/files/image/2010_Toy_Story_3_USLC12_Woody.jpg"/>
    </div>
</div>
 -1
Author: Filo, 2014-07-15 16:06:02