首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何按比例调整图像大小/保持宽高比?

如何按比例调整图像大小/保持宽高比?
EN

Stack Overflow用户
提问于 2010-10-20 03:13:11
回答 18查看 331.6K关注 0票数 186

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

有人能告诉我一些代码,或者解释一下其中的逻辑吗?

EN

回答 18

Stack Overflow用户

回答已采纳

发布于 2010-10-20 03:17:39

看看这段来自http://ericjuden.com/2009/07/jquery-image-resize/的代码

代码语言:javascript
复制
$(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
        }
    });
});
票数 199
EN

Stack Overflow用户

发布于 2013-02-06 22:52:23

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

代码语言:javascript
复制
 /**
  * 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 };
 }
票数 512
EN

Stack Overflow用户

发布于 2012-09-01 05:57:56

如果我没理解错的话,你甚至不需要jQuery来做这件事。仅使用CSS就可以在客户端按比例缩小图像:只需将其max-widthmax-height设置为100%即可。

代码语言:javascript
复制
<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/

票数 73
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3971841

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档