Como redimensionar imagens proporcionalmente / mantendo a proporção?

167

Tenho imagens com dimensões bastante grandes e quero reduzi-las com o jQuery, mantendo as proporções restritas, ou seja, a mesma proporção.

Alguém pode me indicar algum código ou explicar a lógica?

kobe
fonte
4
Você pode explicar por que o jQuery deve ser usado? Existe uma solução somente CSS (veja minha resposta ): defina seu max-widthe max-heightcomo 100%.
Dan Dascalescu 31/08/2012
9
Caso alguém não saiba, se você definir apenas uma dimensão da imagem (largura ou altura), ela será redimensionada proporcionalmente. Tem sido assim desde o início da web. Por exemplo:<img src='image.jpg' width=200>
GetFree
2
Além disso, considere usar algo como slimmage.js para economizar largura de banda e RAM do dispositivo móvel.
Lilith River

Respostas:

188

Veja este código em http://ericjuden.com/2009/07/jquery-image-resize/

$(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
            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
        }
    });
});
Moin Zaman
fonte
1
Desculpe, faltando alguma lógica matemática ... o que acontece quando você precisa aumentar tudo (digamos, você está aumentando o maxHeight)?
Ben
4
Isso pode ser feito apenas com CSS? (máximo de largura, altura: automóvel, etc?)
Tronathan
11
Não sei por que o jQuery é necessário para isso. Reduzir a imagem proporcionalmente no cliente pode ser feito com CSS, e é trivial: basta definir max-widthe max-heightpara 100%. jsfiddle.net/9EQ5c
Dan Dascalescu
10
Isso não pode ser feito com CSS devido ao IF STATEMENT. Eu acredito que o ponto é preencher a imagem em miniatura. Se a imagem for muito alta, ela deverá ter largura máxima, se a imagem for muito larga, ela deverá ter altura máxima. Se você fizer CSS max-width, max-altura, você receberá miniaturas com espaço em branco em vez de totalmente preenchido
ntgCleaner
Esse código pode causar problemas nos navegadores, travar ou diminuir a velocidade?
Déjà Bond
442

Eu acho que esse é um método muito legal :

 /**
  * Conserve aspect ratio of the original region. Useful when shrinking/enlarging
  * images to fit into a certain area.
  *
  * @param {Number} srcWidth width of source image
  * @param {Number} srcHeight height of source image
  * @param {Number} maxWidth maximum available width
  * @param {Number} maxHeight maximum available height
  * @return {Object} { width, height }
  */
function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {

    var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);

    return { width: srcWidth*ratio, height: srcHeight*ratio };
 }
Jason J. Nathan
fonte
33
Resposta vastamente superior! A resposta correta cai de cara se a altura e a largura forem maiores. Realmente, bom, bigode também agradável.
quer
1
Você está certo sobre @sstauross, pixels decimais podem ter resultados ligeiramente inesperados . No meu caso de uso, no entanto, era insignificante. Suponho que Math.floorrealmente vai ajudar com um pixel de perfeita projeto :-)
Jason J. Nathan
1
Obrigado, eu precisava disso quase "one-liner".
Hernán
1
Obrigado Jason, esta resposta realmente me ajudou.
Ashok Shah
4
Essa é uma maneira fantástica de lidar com esse problema! Ajustei um pouco os elementos img + evite ampliar a imagem:function imgSizeFit(img, maxWidth, maxHeight){ var ratio = Math.min(1, maxWidth / img.naturalWidth, maxHeight / img.naturalHeight); img.style.width = img.naturalWidth * ratio + 'px'; img.style.height = img.naturalHeight * ratio + 'px'; }
oriadam 16/18
70

Se entendi a pergunta corretamente, você nem precisa do jQuery para isso. A redução proporcional da imagem no cliente pode ser feita apenas com CSS: basta definir its max-widthe max-heightto 100%.

<div style="height: 100px">
<img src="http://www.getdigital.de/images/produkte/t4/t4_css_sucks2.jpg"
    style="max-height: 100%; max-width: 100%">
</div>​

Aqui está o violino: http://jsfiddle.net/9EQ5c/

Dan Dascalescu
fonte
2
Esta é uma resposta muito mais fácil do que acima. Obrigado. btw, como você conseguiu o link "minha resposta" para rolar até sua postagem?
SnareChops
@ SnareChops: é simplesmente uma âncora HTML .
Dan Dascalescu
1
@SnareChops: se você usar o link fornecido pelo link "compartilhar" sob a resposta, ele também irá rolar para a resposta.
Flimm
1
@ Limlim Como os spans não são exibidos: bloqueie por padrão. Basta adicionar display: block ou torná-lo um div.
mahemoff
1
No meu caso, o IMG foi renderizado com o WordPress, de modo a definir a largura e a altura. Em CSS Eu também tive que conjunto width: auto; height: auto;para obter o seu código em execução :)
lippoliv
12

Para determinar a proporção , é necessário ter uma proporção a ser apontada.

Altura

function getHeight(length, ratio) {
  var height = ((length)/(Math.sqrt((Math.pow(ratio, 2)+1))));
  return Math.round(height);
}

Largura

function getWidth(length, ratio) {
  var width = ((length)/(Math.sqrt((1)/(Math.pow(ratio, 2)+1))));
  return Math.round(width);
}

Neste exemplo, eu uso 16:10desde essa a proporção típica do monitor.

var ratio = (16/10);
var height = getHeight(300,ratio);
var width = getWidth(height,ratio);

console.log(height);
console.log(width);

Os resultados acima seriam 147e300

Rick
fonte
Considerando, 300 = diagonal largura altura = * proporção e a altura é igual à medida que o referido
Johny Pie
6

na verdade, acabei de encontrar esse problema e a solução que encontrei era estranhamente simples e estranha

$("#someimage").css({height:<some new height>})

e milagrosamente a imagem é redimensionada para a nova altura e conservando a mesma proporção!

WindowsMaker
fonte
1
eu acho que isso é útil - mas suponho que não irá restringir a imagem se muito, muito grande dizer, para uma largura máxima ...
stephendwolff
Esse material funciona quando você não define o outro atributo. (largura neste caso)
NoobishPro
4

Existem 4 parâmetros para este problema

  1. largura atual da imagem iX
  2. altura atual da imagem iY
  3. largura da viewport de destino cX
  4. altura da viewport de destino cY

E existem 3 parâmetros condicionais diferentes

  1. cX> cY?
  2. iX> cX?
  3. iY> cY?

solução

  1. Encontre o lado menor da porta de exibição de destino F
  2. Encontre o lado maior da porta de visualização atual L
  3. Encontre o fator de ambos F / L = fator
  4. Multiplique os dois lados da porta atual pelo fator, ou seja, fX = iX *; fator fY = iY *

é tudo o que você precisa fazer.

//Pseudo code


iX;//current width of image in the client
iY;//current height of image in the client
cX;//configured width
cY;//configured height
fX;//final width
fY;//final height

1. check if iX,iY,cX,cY values are >0 and all values are not empty or not junk

2. lE = iX > iY ? iX: iY; //long edge

3. if ( cX < cY )
   then
4.      factor = cX/lE;     
   else
5.      factor = cY/lE;

6. fX = iX * factor ; fY = iY * factor ; 

Este é um fórum maduro, não estou lhe dando código para isso :)

PRASANTH KOLLAIKAL
fonte
2
Postar o método por trás disso é ótimo, mas eu o anotei por não ajudar o usuário publicando o código. Parece um pouco obstrutiva
Doidgey
6
"Alguém pode me indicar algum código ou explicar a lógica?" - Claramente ele estava bem em ter apenas o método explicado a ele. Pessoalmente, acho que essa seria a melhor maneira de ajudar alguém, para ajudá-lo a entender os métodos, em vez de fazê-lo copiar e colar código.
JessMcintosh
@JessMcintosh, pena as edições bazillion para a pergunta original prestado o seu comentário fora de contexto :)
Jason J. Nathan
4

Será que <img src="/path/to/pic.jpg" style="max-width:XXXpx; max-height:YYYpx;" >ajuda?

O navegador cuidará de manter intacta a proporção.

ou seja, max-widthentra em ação quando a largura da imagem é maior que a altura e sua altura será calculada proporcionalmente. Da mesma forma, max-heightentrará em vigor quando a altura for maior que a largura.

Você não precisa de jQuery ou javascript para isso.

Suportado por ie7 + e outros navegadores ( http://caniuse.com/minmaxwh ).

sojin
fonte
Ótima dica! Apenas colocaria o CSS em um arquivo CSS e não diretamente no código html.
Mark
Acho que o problema é que não funcionará quando você não souber qual é a largura e a altura máx. Até que a página seja carregada. É por isso que uma solução JS é necessária. Normalmente é o caso de sites responsivos.
18719 Jason J. Nathan
2

Isso deve funcionar para imagens com todas as proporções possíveis

$(document).ready(function() {
    $('.list img').each(function() {
        var maxWidth = 100;
        var maxHeight = 100;
        var width = $(this).width();
        var height = $(this).height();
        var ratioW = maxWidth / width;  // Width ratio
        var ratioH = maxHeight / height;  // Height ratio

        // If height ratio is bigger then we need to scale height
        if(ratioH > ratioW){
            $(this).css("width", maxWidth);
            $(this).css("height", height * ratioW);  // Scale height according to width ratio
        }
        else{ // otherwise we scale width
            $(this).css("height", maxHeight);
            $(this).css("width", height * ratioH);  // according to height ratio
        }
    });
});
Ajjaah
fonte
2

Aqui está uma correção para a resposta de Mehdiway. A nova largura e / ou altura não estavam sendo definidas para o valor máximo. Um bom caso de teste é o seguinte (1768 x 1075 pixels): http://spacecoastsports.com/wp-content/uploads/2014/06/sportsballs1.png . (Não pude comentar acima devido à falta de pontos de reputação.)

  // Make sure image doesn't exceed 100x100 pixels
  // note: takes jQuery img object not HTML: so width is a function
  // not a property.
  function resize_image (image) {
      var maxWidth = 100;           // Max width for the image
      var maxHeight = 100;          // Max height for the image
      var ratio = 0;                // Used for aspect ratio

      // Get current dimensions
      var width = image.width()
      var height = image.height(); 
      console.log("dimensions: " + width + "x" + height);

      // If the current width is larger than the max, scale height
      // to ratio of max width to current and then set width to max.
      if (width > maxWidth) {
          console.log("Shrinking width (and scaling height)")
          ratio = maxWidth / width;
          height = height * ratio;
          width = maxWidth;
          image.css("width", width);
          image.css("height", height);
          console.log("new dimensions: " + width + "x" + height);
      }

      // If the current height is larger than the max, scale width
      // to ratio of max height to current and then set height to max.
      if (height > maxHeight) {
          console.log("Shrinking height (and scaling width)")
          ratio = maxHeight / height;
          width = width * ratio;
          height = maxHeight;
          image.css("width", width);
          image.css("height", height);
          console.log("new dimensions: " + width + "x" + height);
      }
  }
Tom O'Hara
fonte
2
$('#productThumb img').each(function() {
    var maxWidth = 140; // Max width for the image
    var maxHeight = 140;    // 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 > height){
        height = ( height / width ) * maxHeight;

    } else if(height > width){
        maxWidth = (width/height)* maxWidth;
    }
    $(this).css("width", maxWidth); // Set new width
    $(this).css("height", maxHeight);  // Scale height based on ratio
});
khalid khan
fonte
5
Considere adicionar uma explicação, não apenas o código ao responder uma postagem.
Jørgen R
1

Se a imagem for proporcional, esse código preencherá o wrapper com a imagem. Se a imagem não for proporcional, a largura / altura extra será cortada.

    <script type="text/javascript">
        $(function(){
            $('#slider img').each(function(){
                var ReqWidth = 1000; // Max width for the image
                var ReqHeight = 300; // 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 && height < ReqHeight) {

                    $(this).css("min-height", ReqHeight); // Set new height
                }
                else 
                    if (width > height && width < ReqWidth) {

                        $(this).css("min-width", ReqWidth); // Set new width
                    }
                    else 
                        if (width > height && width > ReqWidth) {

                            $(this).css("max-width", ReqWidth); // Set new width
                        }
                        else 
                            (height > width && width < ReqWidth)
                {

                    $(this).css("min-width", ReqWidth); // Set new width
                }
            });
        });
    </script>
Anu
fonte
1

Sem temporários ou suportes adicionais.

    var width= $(this).width(), height= $(this).height()
      , maxWidth=100, maxHeight= 100;

    if(width > maxWidth){
      height = Math.floor( maxWidth * height / width );
      width = maxWidth
      }
    if(height > maxHeight){
      width = Math.floor( maxHeight * width / height );
      height = maxHeight;
      }

Lembre-se: os mecanismos de pesquisa não gostam, se o atributo width e height não se encaixar na imagem, mas eles não conhecem o JS.

BF
fonte
1

Após algumas tentativas e erros, cheguei a esta solução:

function center(img) {
    var div = img.parentNode;
    var divW = parseInt(div.style.width);
    var divH = parseInt(div.style.height);
    var srcW = img.width;
    var srcH = img.height;
    var ratio = Math.min(divW/srcW, divH/srcH);
    var newW = img.width * ratio;
    var newH = img.height * ratio;
    img.style.width  = newW + "px";
    img.style.height = newH + "px";
    img.style.marginTop = (divH-newH)/2 + "px";
    img.style.marginLeft = (divW-newW)/2 + "px";
}
Roland Hentschel
fonte
1

O redimensionamento pode ser alcançado (mantendo a proporção) usando CSS. Esta é uma resposta mais simplificada, inspirada no post de Dan Dascalescu.

http://jsbin.com/viqare

img{
     max-width:200px;
 /*Or define max-height*/
  }
<img src="http://e1.365dm.com/13/07/4-3/20/alastair-cook-ashes-profile_2967773.jpg"  alt="Alastair Cook" />

<img src="http://e1.365dm.com/13/07/4-3/20/usman-khawaja-australia-profile_2974601.jpg" alt="Usman Khawaja"/>

pressa dee
fonte
1

2 Passos:

Etapa 1) calcule a proporção da largura / altura do original da imagem.

Etapa 2) multiplique a proporção original_width / original_height pela nova altura desejada para obter a nova largura correspondente à nova altura.

Hitesh Ranaut
fonte
0

Este problema pode ser resolvido por CSS.

.image{
 max-width:*px;
}
ravinder banoth
fonte
-4

Isso funcionou totalmente para mim para um item arrastável - aspectRatio: true

.appendTo(divwrapper).resizable({
    aspectRatio: true,
    handles: 'se',
    stop: resizestop 
})
Catherine
fonte