jQuery调整图像大小

44
我想开始一场关于使用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
    }
});

});


你有没有想过为什么 var maxWidth = $(document).width(); 不能正常工作?看一下这个链接:http://jsfiddle.net/KHdZG/16/ - Mike
2
由于jQuery/javascript在客户端运行,如果服务器上的文件大小为2 MB,则浏览器仍然必须下载完整的2 MB才能呈现100x100像素的图像。正确吗? - user153923
14个回答

27

在第一个条件之后,您需要重新计算宽度和高度。以下是整个脚本的代码:

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

2
你忘记用 }); 关闭外部函数了。 - DarkNeuron
为什么您在if块的最后几行设置高度和宽度?在 height = height * ratio; 之后,您不是会用 var height = $(this).height(); 重写它吗?谢谢。 - ksclarke

11

一些建议:

  • 将其制作成函数,您可以传入一个最大或最小尺寸,而不是硬编码;这将使它更可重复使用。
  • 如果您使用jQuery的.animate方法,例如.animate({width:maxWidth}),它应该会自动缩放其他维度。

1
使用 jQuery 的 .animate 方法只能让你按一个维度进行缩放。换句话说,我无法设置最大宽度和最大高度。 - davekaro
2
@davekaro - 来自文档:“例如,我们可以同时动画化宽度和高度...” http://api.jquery.com/animate/ - Nathan Long
关于使用.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
            }
        }
    });
});

这样做的好处是您可以同时指定宽度和高度,同时允许图像按比例缩放。

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

这里应该加上一些解释会更好。 - Andrew Barber
3
有评论,无需解释。好的解决方案 Miehz :) - Jonathan Marzullo

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,则进行相应处理。


图像大小在加载完成后才可用,因此我将上面的代码与此代码结合使用,效果很好:https://dev59.com/pm865IYBdhLWcg3wUs3z#3877079 - g1ga

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

1
通常情况下,一定要添加一些文本来解释你所做的更改以及原因。不要强迫读者比较每一行代码,看看你做了什么修改,并猜测为什么你的更改更好。 - Devon_C_Miller

2

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
您可以使用以下代码调整图像大小。
    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));
        }
   });

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接