Pregunta

¿Cómo puedo cambiar el tamaño de una imagen en jQuery a una relación de aspecto consistente. Por ejemplo el establecimiento de la altura máxima y tienen la anchura de cambiar el tamaño correctamente. Gracias.

¿Fue útil?

Solución

Se puede calcular de forma manual,

es decir:.

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

Asegúrese de que utiliza los valores originales de la imagen de lo contrario se degradan con el tiempo.

EDIT: ejemplo versión jQuery (no probado)

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

Otros consejos

Esta es una función útil que puede hacer lo que quiera:

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

Básicamente, se agarra un elemento, lo centra dentro de la matriz, a continuación, se extiende para que se ajuste de tal manera que ninguno de los antecedentes de los padres es visible, mientras se mantiene la relación de aspecto.

Por otra parte, esto podría no ser lo que quiere hacer.

jQueryUI de Resizeable

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

aspectRatio: true -> mantener la relación de aspecto original

No hay contabilidad de la cantidad de copias y de los parches los que hay eh! También quería saber esto y todo lo que vi eran interminables ejemplos de anchura o la altura de escala .. que se quieren desbordar la otra?

  • cambiar la anchura y la altura sin necesidad de un bucle
  • No excede las dimensiones originales imágenes
  • Utiliza las matemáticas que funciona correctamente es decir la anchura / altura de aspecto, y la altura * aspecto de ancho para que las imágenes son en realidad una escala correcta de arriba a abajo: /

Debe ser lo suficientemente sencillo para convertir a javascript u otros idiomas

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

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 es una buena solución si necesita altura perfecta y relación de aspecto ancho tras cosecha dará relación de cultivo perfecto

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 bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top