动态缩放图像以适应指定的宽度和高度大小

9

经过大量的研究和使用jQuery和Javascript等技术,我无法找到一种动态缩放图像以适应指定大小的方法,既可以水平又可以垂直地缩放。我发现了大量关于按比例缩放以适应宽度或按比例缩放以适应高度的信息,但是无法确定图像是太高还是太矮并进行相应的调整。

所以在我的示例中,我有一个设置宽度为460px和高度为280px的<div>,我需要这个图像完全适合这个区域而不拉伸(保持其纵横比)。


我编写了一个 jQuery 插件来处理这种事情,也许可以帮到你:https://dev59.com/23bZa4cB1Zd3GeqPLelM#25222380 - Drew Baker
2个回答

28

在尝试了一些宽度示例后,我开始运用我的经典代数技巧。

如果我将宽度除以高度,例如在此情况下是460/280,则会得到1.642...,这是该区域的长宽比。现在,如果我查看图像的长宽比,我知道如果它大于1.642...,那么意味着它比该区域更宽,如果图像的长宽比小于1.642...,那么它则更高。

因此,我得出了以下结论,

// Set the Image in question
$image = 'img/gif/b47rz.gif';

// Set the width of the area and height of the area
$inputwidth = 460;
$inputheight = 280;

// Get the width and height of the Image
list($width,$height) = getimagesize($image);

// So then if the image is wider rather than taller, set the width and figure out the height
if (($width/$height) > ($inputwidth/$inputheight)) {
            $outputwidth = $inputwidth;
            $outputheight = ($inputwidth * $height)/ $width;
        }
// And if the image is taller rather than wider, then set the height and figure out the width
        elseif (($width/$height) < ($inputwidth/$inputheight)) {
            $outputwidth = ($inputheight * $width)/ $height;
            $outputheight = $inputheight;
        }
// And because it is entirely possible that the image could be the exact same size/aspect ratio of the desired area, so we have that covered as well
        elseif (($width/$height) == ($inputwidth/$inputheight)) {
            $outputwidth = $inputwidth;
            $outputheight = $inputheight;
            }
// Echo out the results and done
echo '<img src="'.$image.'" width="'.$outputwidth.'" height="'.$outputheight.'">';

它完美地运行了,所以我想分享一下,希望这能对一些人有帮助


1
您先生真是救命恩人 +1 - user1130272
1
我在谷歌上搜索同样的问题,然后发现了你的函数,它非常好用,为我节省了很多时间!非常感谢你! :-) - P.Davide

2
如果我理解你的问题正确,缩放图片的更简单的方法是使用以下CSS样式规则:
max-width
max-height

这两个样式规则允许您指定图像的最大宽度/高度。浏览器将缩小图像(保持长宽比)以适应您指定的大小。您还可以使用这两个规则来指定图像的最小宽度/高度:

min-width
min-height

是的,非常正确,但它没有保持纵横比,可能是我做错了,但这导致我自己编写了一个小脚本在php中完成它。 - Chris James Champeau
如果您使用上述CSS样式规则(而不是widthheight),它应该始终保持纵横比。如果没有,那么在管道的某个地方似乎存在错误。请检查在线演示。如果仍然无法保持纵横比,则应向您正在使用的浏览器的浏览器供应商报告错误。 - starbeamrainbowlabs
谢谢,但我不太担心这个问题,我真的很喜欢下面使用PHP风格的方法。 - Chris James Champeau

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