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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3971841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:55:45  来源:igfitidea点击:

How to resize images proportionally / keeping the aspect ratio?

javascriptjqueryimageresize

提问by kobe

I have images that will be quite big in dimension and I want to shrink them down with jQuery while keeping the proportions constrained, i.e. the same aspect ratio.

我有尺寸很大的图像,我想用 jQuery 缩小它们,同时保持比例受限,即相同的纵横比。

Can someone point me to some code, or explain the logic?

有人可以指点我一些代码,或者解释一下逻辑吗?

回答by Jason J. Nathan

I think this is a really 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 };
 }

回答by Moin Zaman

Have a look at this piece of code from http://ericjuden.com/2009/07/jquery-image-resize/

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

回答by Dan Dascalescu

If I understand the question correctly, you don't even need jQuery for this. Shrinking the image proportionally on the client can be done with CSS alone: just set its max-widthand max-heightto 100%.

如果我正确理解了这个问题,那么您甚至不需要 jQuery。在客户端按比例缩小图像可以单独使用 CSS 完成:只需将其max-width和设置max-height100%

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

Here's the fiddle: http://jsfiddle.net/9EQ5c/

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

回答by Rick

In order to determine the aspect ratio, you need to have a ratio to aim for.

为了确定纵横比,您需要有一个目标比例。

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

In this example I use 16:10since this the typical monitor aspect ratio.

在这个例子中,我使用16:10了典型的显示器纵横比。

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

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

Results from above would be 147and 300

上面的结果将是147300

回答by WindowsMaker

actually i have just run into this problem and the solution I found was strangely simple and weird

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

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

and miraculously the image is resized to the new height and conserving the same ratio!

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

回答by PRASANTH KOLLAIKAL

There are 4 parameters to this problem

这个问题有4个参数

  1. current image width iX
  2. current image height iY
  3. target viewport width cX
  4. target viewport height cY
  1. 当前图像宽度 iX
  2. 当前图像高度 iY
  3. 目标视口宽度 cX
  4. 目标视口高度 cY

And there are 3 different conditional parameters

并且有 3 个不同的条件参数

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

solution

解决方案

  1. Find the smaller side of the target view port F
  2. Find the larger side of the current view port L
  3. Find the factor of both F/L = factor
  4. Multiply both sides of the current port with the factor ie, fX = iX * factor; fY = iY * factor
  1. 找到目标视口 F 的较小一侧
  2. 找到当前视口 L 的较大一侧
  3. 求两个 F/L = factor 的因子
  4. 将当前端口的两边乘以因子即,fX = iX * 因子;fY = iY * 因子

that's all you need to do.

这就是你需要做的。

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

This is a mature forum, I am not giving you code for that :)

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

回答by sojin

Does <img src="/path/to/pic.jpg" style="max-width:XXXpx; max-height:YYYpx;" >help?

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

Browser will take care of keeping aspect ratio intact.

浏览器将负责保持纵横比不变。

i.e max-widthkicks in when image width is greater than height and its height will be calculated proportionally. Similarly max-heightwill be in effect when height is greater than width.

max-width当图像宽度大于高度时启动,其高度将按比例计算。max-height当高度大于宽度时同样有效。

You don't need any jQuery or javascript for this.

为此,您不需要任何 jQuery 或 javascript。

Supported by ie7+ and other browsers (http://caniuse.com/minmaxwh).

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

回答by Ajjaah

This should work for images with all possible proportions

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

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

回答by Tom O'Hara

Here's a correction to Mehdiway's answer. The new width and/or height were not being set to the max value. A good test case is the following (1768 x 1075 pixels): http://spacecoastsports.com/wp-content/uploads/2014/06/sportsballs1.png. (I wasn't able to comment on it above due to lack of reputation points.)

这是对 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);
      }
  }

回答by khalid khan

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