2009-07-17 10 views
39

Je voudrais commencer une discussion sur le redimensionnement de l'image à l'aide de jQuery.Redimensionnement de l'image Jquery

C'est ma contribution: Mais je pense que je suis loin de la solution. Qu'en est-il du recadrage? Qui peut m'aider?

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

});

+0

Avez-vous une idée pourquoi ce won ne fonctionne pas avec 'var maxWidth = $ (document) .width();'. Jetez un oeil: http://jsfiddle.net/KHdZG/16/ – Mike

+2

Depuis jQuery/javascript s'exécute dans le client, si un fichier sur le serveur est de 2 Mo, le navigateur doit encore télécharger le plein 2 Mo avant de rendre un 100x100 image. Correct? – jp2code

Répondre

10

Quelques suggestions:

  • Faire cette fonction où vous pouvez passer une taille maximale ou minimale, plutôt que de coder en dur il; cela le rendra plus réutilisable
  • Si vous utilisez la méthode .animate de jQuery, comme .animate({width: maxWidth}), l'autre dimension doit automatiquement être redimensionnée pour vous.
+1

L'utilisation de la méthode jQuery .animate vous permet uniquement de dimensionner une dimension. En d'autres termes, je ne peux pas définir maxWidth et maxHeight. – davekaro

+2

@davekaro - à partir des docs: "Nous pouvons, par exemple, animer simultanément la largeur et la hauteur ..." http://api.jquery.com/animate/ –

+0

Belle prise sur l'utilisation de .animate() comme ça, était totalement inconscient qu'il devrait mettre à l'échelle l'autre dimension - en gardant le rapport d'aspect correct pour vous. – Moddy

6

Démarrage rapide. Voici ce que je suis venu avec:

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

Ceci a l'avantage de vous permettre de spécifier la largeur et la hauteur tout en permettant l'image à l'échelle proportionnellement encore.

25

Vous devez recalculer la largeur et la hauteur après la première condition. Voici le code de script entier:

$(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 
    } 
}); 
+1

Vous avez oublié de fermer la fonction externe avec}); – DarkNeuron

+0

Pourquoi définissez-vous la hauteur et la largeur dans les dernières lignes des blocs if? Après avoir fait 'height = height * ratio;' ne pas le remplacer par 'var height = $ (this) .height();' juste en dehors du bloc if? Merci. – ksclarke

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

En règle générale, ajoutez toujours du texte expliquant ce que vous avez changé et pourquoi. Ne forcez pas le lecteur à comparer chaque ligne pour voir ce que vous avez changé et faites des suppositions pour expliquer pourquoi votre changement est meilleur. –

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

qui fera le tour de magie pour tout le monde en utilisant la dernière jquery. Assurez-vous de bien régler votre sélecteur (j'ai utilisé $ ('img') mais cela peut être différent dans votre cas). Cela ne fonctionne que pour le mode paysage. Mais si vous regardez, seulement quelques choses doivent être fait pour le mettre au portrait, alias, si img.height()> maxHeight) choses

+0

La taille de l'image est disponible après chargement terminé, donc j'ai utilisé le code ci-dessus en combinaison avec celui-ci et cela a bien fonctionné: http://stackoverflow.com/a/3877079/733749 – g1ga

5
$(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 
    } 
    }); 
}); 
+0

Quelques explications auraient été bien ici –

+3

il y a des commentaires .. pas besoin d'une explication .. Bonne solution Miehz :) –

0

réponse de modification Aleksandar pour faire comme plugin jquery et accepte maxwidth et maxheight comme arguments, suggérés par 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; 
    } 
}); 
}; 

Utilisé comme $('.imgClass').resize(300,50);

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

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

imgLiquid (un plugin jQuery) semble faire ce que vous demandez.

Démo:
http://goo.gl/Wk8bU

exemple 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> 
0

et ancien poste ... peu encore. Le redimensionnement est une chose, mais il peut laisser des images redimensionnées sans être centrées et avoir l'air un peu désorganisé. J'ai donc ajouté quelques lignes à la publication originale pour ajouter une marge de gauche pour centraliser les images redimensionnées.

$(".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

Code Tant et si bien ici, mais je pense que cela est la meilleure réponse

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

Vous pouvez redimensionner l'image avec ce morceau de code

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