如何按比例调整图像大小/保持纵横比?

时间:2010-10-19 19:13:11

标签: javascript jquery image resize

我的图像尺寸相当大,我想用jQuery缩小它们,同时保持比例受限,即相同的宽高比。

有人能指点我一些代码,还是解释逻辑?

19 个答案:

答案 0 :(得分:382)

我认为这是一个真正的cool method

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

答案 1 :(得分:165)

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

答案 2 :(得分:63)

如果我正确理解了这个问题,你甚至不需要jQuery。在客户端上按比例缩小图像可以仅使用CSS完成:只需将其max-widthmax-height设置为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>​

这是小提琴:http://jsfiddle.net/9EQ5c/

答案 3 :(得分:10)

为了确定aspect ratio,您需要有一个目标比率。

Height

1

Width

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

在此示例中,我使用function getWidth(length, ratio) { var width = ((length)/(Math.sqrt((1)/(Math.pow(ratio, 2)+1)))); return Math.round(width); } ,因为这是典型的监视器宽高比。

16:10

上面的结果是var ratio = (16/10); var height = getHeight(300,ratio); var width = getWidth(height,ratio); console.log(height); console.log(width); 147

答案 4 :(得分:6)

实际上我遇到了这个问题,我发现的解决方案非常简单和奇怪

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

并奇迹般地将图像调整到新的高度并保持相同的比例!

答案 5 :(得分:4)

此问题有4个参数

  1. 当前图片宽度iX
  2. 当前图像高度iY
  3. 目标视口宽度cX
  4. 目标视口高度cY
  5. 并且有3种不同的条件参数

    1. cX&gt; cY?
    2. iX&gt; cX?
    3. iY&gt; cY?
    4. 溶液

      1. 找到目标视口F
      2. 的较小边
      3. 找到当前视口L的较大一侧
      4. 找出F / L = factor
      5. 的因子
      6. 将当前端口的两侧乘以因子,即fX = iX * factor; fY = iY * factor
      7. 这就是你需要做的一切。

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

        这是一个成熟的论坛,我没有给你代码:)

答案 6 :(得分:4)

<img src="/path/to/pic.jpg" style="max-width:XXXpx; max-height:YYYpx;" >有帮助吗?

浏览器会保持宽高比保持不变。

当图像宽度大于高度时,

max-width开始,其高度将按比例计算。同样,当高度大于宽度时,max-height将生效。

你不需要任何jQuery或javascript。

ie7 +和其他浏览器(http://caniuse.com/minmaxwh)支持。

答案 7 :(得分:2)

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

答案 8 :(得分:2)

这适用于所有可能比例的图像

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

答案 9 :(得分:1)

如果图像是比例的,那么此代码将用图像填充包装器。如果图像不成比例,则会裁剪额外的宽度/高度。

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

答案 10 :(得分:1)

这是对Mehdiway回答的修正。新宽度和/或高度未设置为最大值。一个好的测试用例如下(1768 x 1075像素):http://spacecoastsports.com/wp-content/uploads/2014/06/sportsballs1.png。 (由于缺乏声誉点,我上面无法发表评论。)

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

答案 11 :(得分:1)

可以使用CSS实现调整大小(保持宽高比)。 这是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"/>

答案 12 :(得分:1)

经过一些试验和错误后,我来到了这个解决方案:

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

答案 13 :(得分:1)

没有额外的临时工具或括号。

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

请记住:如果width和height属性不适合图像,搜索引擎不喜欢它,但他们不了解JS。

答案 14 :(得分:0)

看看这篇文章......

/**
 * @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
    };
}

答案 15 :(得分:0)

2个步骤:

步骤1)计算图像的原始宽度/原始高度的比率。

第2步)将original_width / original_height比值乘以新的所需高度,以获得与新高度相对应的新宽度。

答案 16 :(得分:0)

此问题可以通过CSS解决。

.image{
 max-width:*px;
}

答案 17 :(得分:0)

调整大小以适合容器,获取比例因子,缩小百分比控制

 $(function () {
            let ParentHeight = 200;
            let ParentWidth = 300;
            $("#Parent").width(ParentWidth).height(ParentHeight);
            $("#ParentHeight").html(ParentHeight);
            $("#ParentWidth").html(ParentWidth);

            var RatioOfParent = ParentHeight / ParentWidth;
            $("#ParentAspectRatio").html(RatioOfParent);

            let ChildHeight = 2000;
            let ChildWidth = 4000;
            var RatioOfChild = ChildHeight / ChildWidth;
            $("#ChildAspectRatio").html(RatioOfChild);

            let ScaleHeight = ParentHeight / ChildHeight;
            let ScaleWidth = ParentWidth / ChildWidth;
            let Scale = Math.min(ScaleHeight, ScaleWidth);

            $("#ScaleFactor").html(Scale);
            // old scale
            //ChildHeight = ChildHeight * Scale;
            //ChildWidth = ChildWidth * Scale;

            // reduce scale by 10%, you can change the percentage
            let ScaleDownPercentage = 10;
            let CalculatedScaleValue = Scale * (ScaleDownPercentage / 100);
            $("#CalculatedScaleValue").html(CalculatedScaleValue);

            // new scale
            let NewScale = (Scale - CalculatedScaleValue);
            ChildHeight = ChildHeight * NewScale;
            ChildWidth = ChildWidth * NewScale;

            $("#Child").width(ChildWidth).height(ChildHeight);
            $("#ChildHeight").html(ChildHeight);
            $("#ChildWidth").html(ChildWidth);

        });
        #Parent {
            background-color: grey;
        }

        #Child {
            background-color: red;
        }
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Parent">
    <div id="Child"></div>
</div>

<table>
    <tr>
        <td>Parent Aspect Ratio</td>
        <td id="ParentAspectRatio"></td>
    </tr>
    <tr>
        <td>Child Aspect Ratio</td>
        <td id="ChildAspectRatio"></td>
    </tr>
    <tr>
        <td>Scale Factor</td>
        <td id="ScaleFactor"></td>
    </tr>
    <tr>
        <td>Calculated Scale Value</td>
        <td id="CalculatedScaleValue"></td>
    </tr>
    <tr>
        <td>Parent Height</td>
        <td id="ParentHeight"></td>
    </tr>
    <tr>
        <td>Parent Width</td>
        <td id="ParentWidth"></td>
    </tr>
    <tr>
        <td>Child Height</td>
        <td id="ChildHeight"></td>
    </tr>
    <tr>
        <td>Child Width</td>
        <td id="ChildWidth"></td>
    </tr>
</table>

答案 18 :(得分:-4)

这对我来说对于一个可拖动的项目来说非常有用 - aspectRatio:true

.appendTo(divwrapper).resizable({
    aspectRatio: true,
    handles: 'se',
    stop: resizestop 
})