Pergunta

Como eu poderia redimensionar uma imagem no jQuery para uma proporção consistente. Por exemplo definindo altura máxima e têm o redimensionamento largura corretamente. Obrigado.

Foi útil?

Solução

Você poderia calcular isso manualmente,

ou seja:.

function GetWidth(newHeight,orginalWidth,originalHeight)
{
if(currentHeight == 0)return newHeight;
var aspectRatio = currentWidth / currentHeight;
return newHeight * aspectRatio;
}

Certifique-se de usar os valores originais para a imagem caso contrário ele irá degradar ao longo do tempo.

EDIT: exemplo versão jQuery (não testado)

jQuery.fn.resizeHeightMaintainRatio = function(newHeight){
    var aspectRatio = $(this).data('aspectRatio');
    if (aspectRatio == undefined) {
        aspectRatio = $(this).width() / $(this).height();
        $(this).data('aspectRatio', aspectRatio);
    }
    $(this).height(newHeight); 
    $(this).width(parseInt(newHeight * aspectRatio));
}

Outras dicas

Aqui está uma função útil que pode fazer o que quiser:

jQuery.fn.fitToParent = function()
{
    this.each(function()
    {
        var width  = $(this).width();
        var height = $(this).height();
        var parentWidth  = $(this).parent().width();
        var parentHeight = $(this).parent().height();

        if(width/parentWidth < height/parentHeight) {
            newWidth  = parentWidth;
            newHeight = newWidth/width*height;
        }
        else {
            newHeight = parentHeight;
            newWidth  = newHeight/height*width;
        }
        var margin_top  = (parentHeight - newHeight) / 2;
        var margin_left = (parentWidth  - newWidth ) / 2;

        $(this).css({'margin-top' :margin_top  + 'px',
                     'margin-left':margin_left + 'px',
                     'height'     :newHeight   + 'px',
                     'width'      :newWidth    + 'px'});
    });
};

Basicamente, ele agarra um elemento, centros-lo dentro da matriz, em seguida, se estende para encaixar de modo a que nenhum dos fundo do pai é visível, enquanto se mantém a relação de aspecto.

Então, novamente, isso pode não ser o que você quer fazer.

Use jQueryUI Resizeable

$("#some_image").resizable({ aspectRatio:true, maxHeight:300 });

aspectRatio: true -> manter a proporção original

Não há nenhuma representando a quantidade de cópia e pasters lá fora, eh! Eu também queria saber isso e tudo o que vi foram exemplos intermináveis ??de dimensionamento largura ou altura .. que gostariam outro transbordamento?!

  • largura redimensionar e altura sem a necessidade de um loop
  • não exceda as imagens dimensões originais
  • Usa matemática que funciona adequadamente ou seja largura / aspecto de altura e altura * aspecto de largura para que as imagens são realmente escalado adequadamente cima e para baixo: /

Deve ser suficiente para a frente para converter em javascript ou outras línguas

//////////////

private void ResizeImage(Image img, double maxWidth, double maxHeight)
{
    double srcWidth = img.Width;
    double srcHeight = img.Height;

    double resizeWidth = srcWidth;
    double resizeHeight = srcHeight;

    double aspect = resizeWidth / resizeHeight;

    if (resizeWidth > maxWidth)
    {
        resizeWidth = maxWidth;
        resizeHeight = resizeWidth / aspect;
    }
    if (resizeHeight > maxHeight)
    {
        aspect = resizeWidth / resizeHeight;
        resizeHeight = maxHeight;
        resizeWidth = resizeHeight * aspect;
    }

    img.Width = resizeWidth;
    img.Height = resizeHeight;
}

Esta é uma boa solução se você precisa de aperfeiçoar altura e proporção largura após a colheita vai dar proporção de corte perfeito

getPerfectRatio(img,widthRatio,heightRatio){

  if(widthRatio < heightRatio){
    var height = img.scalingHeight - (img.scalingHeight % heightRatio);
    var finalHeight = height
    var finalWidth = widthRatio * (height/heightRatio);

    img.cropHeight = finalHeight;
    img.cropWidth = finalWidth
  }
  if(heightRatio < widthRatio){;
    var width = img.scalingWidth - (img.scalingWidth % widthRatio);
    var finalWidth = width;
    var finalHeight  = heightRatio * (width/widthRatio);
    img.cropHeight = finalHeight;
    img.cropWidth = finalWidth
  }

  return img
  
}

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top