2009-07-17 9 views
39

Я хотел бы начать обсуждение изменения размера изображения с помощью jQuery.JQuery Изменение размера изображения

Это мой вклад: Но я думаю, что я далеко от решения. Как насчет обрезки? Кто может мне помочь?

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

Есть ли у вас какие-либо идеи, почему это вона 't работать с 'var maxWidth = $ (document) .width();'. Посмотрите: http://jsfiddle.net/KHdZG/16/ – Mike

+2

Поскольку jQuery/javascript запускается на клиенте, если файл на сервере составляет 2 МБ, браузер все равно должен загружать полные 2 МБ перед рендерингом 100х100 образ. Верный? – jp2code

ответ

10

Несколько предложений:

  • Сделать это функцией, где вы можете пройти в макс или мин размере, а не жесткое кодирование его; что сделает его более многоразовым
  • Если вы используете метод jQuery, например .animate({width: maxWidth}), он должен автоматически масштабировать другое измерение.
+1

Использование метода jQuery .animate позволяет масштабировать только одно измерение. Другими словами, я не могу установить maxWidth и maxHeight. – davekaro

+2

@ davekaro - из документов: «Мы можем, например, одновременно анимировать ширину и высоту ...» http://api.jquery.com/animate/ –

+0

Приятно поймать использование .animate(), как это, было полностью не осознавая, что он должен масштабировать другое измерение - сохраняя соотношение сторон правильно для вас. – Moddy

6

Отличный старт. Вот что я придумал:

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

Это имеет преимущество позволяет задавать и ширину и высоту, позволяя изображения по-прежнему масштабировать пропорционально.

25

Вам необходимо пересчитать ширину и высоту после первого условия. Вот код всего сценария:

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

Вы забыли закрыть внешнюю функцию с помощью}); – DarkNeuron

+0

Почему вы устанавливаете высоту и ширину в последних строках блоков if? После того, как вы выполняете соотношение height = height *, вы не переопределяете это с помощью переменной var height = $ (this) .height(); 'прямо вне блока if? Благодарю. – 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

Как правило, всегда добавляйте текст, объясняющий, что вы изменили и почему. Не заставляйте читателя сравнивать каждую строку, чтобы увидеть, что вы изменили, и догадываться, почему ваши изменения лучше. –

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

что сделает магический трюк для всех, кто использует последнюю версию JQuery. Убедитесь, что вы правильно настроили селектор (я использовал $ ('img'), но в вашем случае это может быть другим). Это работает только в ландшафтном режиме. Но если вы посмотрите на нее, только несколько вещей, которые должны быть сделаны, чтобы установить его портрет, он же, если img.height()> MaxHeight) материал

+0

Размер изображения доступен после завершения загрузки, поэтому я использовал код выше в сочетании с этим, и он работал хорошо: 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

Некоторые объяснения были бы хорошими здесь –

+3

есть комментарии .. нет необходимости в объяснении .. Хорошее решение Miehz :) –

0

ответ Модифицируйте Александар, чтобы сделать его как JQuery плагин и принимает maxwidth и maxheight в качестве аргументов, предложенных Нафаном.

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

Используется как $('.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 (плагин jQuery), похоже, делает то, что вы просите.

Демо:
http://goo.gl/Wk8bU

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

И старый пост ... немного еще. Изменение размера - это одно, но оно может оставлять измененные изображения без внимания и выглядеть немного неорганизованными. Поэтому я добавил несколько строк в исходное сообщение, чтобы добавить левый край, чтобы централизовать любые измененные изображения.

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

Так много коды, но я думаю, что это лучший ответ

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

Вы можете изменить размер изображения с этой частью кода

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)); 
     } 
    }); 
Смежные вопросы