web-dev-qa-db-fra.com

Comment redimensionner les images proportionnellement/en maintenant le format de l'image?

J'ai des images de dimensions assez grandes et je veux les réduire avec jQuery tout en maintenant les proportions, c’est-à-dire le même rapport de format.

Quelqu'un peut-il m'indiquer un code ou expliquer la logique?

139
kobe

Regardez ce morceau de code de 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
        }
    });
});
165
Moin Zaman

Je pense que c'est une méthode vraiment cool :

 /**
  * 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 };
 }
367
Jason J. Nathan

Si je comprends bien la question, vous n’avez même pas besoin de jQuery pour cela. La réduction proportionnelle de l'image sur le client peut être réalisée avec CSS uniquement: il suffit de définir ses max-width et max-height sur 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>​

Voici le violon: http://jsfiddle.net/9EQ5c/

61
Dan Dascalescu

Afin de déterminer le rapport d'aspect , vous devez avoir un rapport de visée. 

Height

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

Width

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

Dans cet exemple, j’utilise 16:10 puisque c’est le format d’image typique du moniteur.

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

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

Les résultats ci-dessus seraient 147 et 300

9
Rick

en fait, je viens de rencontrer ce problème et la solution que j'ai trouvée était étrangement simple et étrange

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

et miraculeusement, l'image est redimensionnée à la nouvelle hauteur tout en conservant le même rapport!

6
WindowsMaker

Il y a 4 paramètres à ce problème

  1. largeur de l'image actuelle iX
  2. hauteur de l'image actuelle iY
  3. largeur de la fenêtre cible cX
  4. hauteur de la fenêtre cible cY

Et il y a 3 paramètres conditionnels différents

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

solution

  1. Trouver le plus petit côté du port de vue cible F
  2. Trouver le plus grand côté du port d'affichage actuel L
  3. Trouver le facteur des deux F/L = facteur
  4. Multipliez les deux côtés du port actuel avec le facteur, c.-à-d. FX = facteur iX *; fY = iY * facteur

c'est tout ce que vous devez faire.

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

Ceci est un forum mature, je ne vous donne pas le code pour ça :)

4

Est-ce que <img src="/path/to/pic.jpg" style="max-width:XXXpx; max-height:YYYpx;" > aide?

Le navigateur se chargera de garder les proportions intactes. 

i.e max-width entre en action lorsque la largeur de l'image est supérieure à la hauteur et que sa hauteur est calculée proportionnellement. De même, max-height sera en vigueur lorsque la hauteur est supérieure à la largeur.

Vous n'avez pas besoin de jQuery ou javascript pour cela.

Pris en charge par ie7 + et d’autres navigateurs ( http://caniuse.com/minmaxwh ).

4
sojin
$('#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
});
2
khalid khan

Cela devrait fonctionner pour des images avec toutes les proportions possibles

$(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
        }
    });
});
2
Ajjaah

Le redimensionnement peut être réalisé (en maintenant les proportions) en utilisant CSS. C’est une réponse simplifiée supplémentaire inspirée du message 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"/>

1
rush dee

Après quelques essais et erreurs, je suis arrivé à cette solution:

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";
}
1
Roland Hentschel

Sans temp-vars ni crochets supplémentaires.

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

N'oubliez pas: les moteurs de recherche ne l'aiment pas si les attributs width et height ne correspondent pas à l'image, mais ils ne connaissent pas JS. 

1
B.F.

Si l'image est proportionnée, ce code remplira l'encapsuleur d'image. Si l'image n'est pas proportionnelle, la largeur et la hauteur supplémentaires seront rognées.

    <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>
1
Anu

Voici une correction à la réponse de Mehdiway. Les nouvelles largeur et/ou hauteur n'étaient pas définies sur la valeur maximale. Un bon test est le suivant (1768 x 1075 pixels): http://spacecoastsports.com/wp-content/uploads/2014/06/sportsballs1.png . (Je n'ai pas pu commenter ci-dessus à cause du manque de points de réputation.)

  // 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);
      }
  }
1
Tom O'Hara

2 étapes:

Étape 1) Calculez le rapport largeur/hauteur d'origine de l'image.

Étape 2) multiplier le rapport original_width/original_height par la nouvelle hauteur souhaitée pour obtenir la nouvelle largeur correspondant à la nouvelle hauteur.

0
Hitesh Ranaut

Regardez cette pièce ...

/**
 * @param {Number} width
 * @param {Number} height
 * @param {Number} destWidth
 * @param {Number} destHeight
 * 
 * @return {width: Number, height:Number}
 */
function resizeKeepingRatio(width, height, destWidth, destHeight)
{
    if (!width || !height || width <= 0 || height <= 0)
    {
        throw "Params error";
    }
    var ratioW = width / destWidth;
    var ratioH = height / destHeight;
    if (ratioW <= 1 && ratioH <= 1)
    {
        var ratio = 1 / ((ratioW > ratioH) ? ratioW : ratioH);
        width *= ratio;
        height *= ratio;
    }
    else if (ratioW > 1 && ratioH <= 1)
    {
        var ratio = 1 / ratioW;
        width *= ratio;
        height *= ratio;
    }
    else if (ratioW <= 1 && ratioH > 1)
    {
        var ratio = 1 / ratioH;
        width *= ratio;
        height *= ratio;
    }
    else if (ratioW >= 1 && ratioH >= 1)
    {
        var ratio = 1 / ((ratioW > ratioH) ? ratioW : ratioH);
        width *= ratio;
        height *= ratio;
    }
    return {
        width : width,
        height : height
    };
}
0
noopmk