经过大量的研究和使用jQuery和Javascript等技术,我无法找到一种动态缩放图像以适应指定大小的方法,既可以水平又可以垂直地缩放。我发现了大量关于按比例缩放以适应宽度或按比例缩放以适应高度的信息,但是无法确定图像是太高还是太矮并进行相应的调整。
所以在我的示例中,我有一个设置宽度为460px和高度为280px的<div>
,我需要这个图像完全适合这个区域而不拉伸(保持其纵横比)。
经过大量的研究和使用jQuery和Javascript等技术,我无法找到一种动态缩放图像以适应指定大小的方法,既可以水平又可以垂直地缩放。我发现了大量关于按比例缩放以适应宽度或按比例缩放以适应高度的信息,但是无法确定图像是太高还是太矮并进行相应的调整。
所以在我的示例中,我有一个设置宽度为460px和高度为280px的<div>
,我需要这个图像完全适合这个区域而不拉伸(保持其纵横比)。
在尝试了一些宽度示例后,我开始运用我的经典代数技巧。
如果我将宽度除以高度,例如在此情况下是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.'">';
它完美地运行了,所以我想分享一下,希望这能对一些人有帮助
max-width
max-height
这两个样式规则允许您指定图像的最大宽度/高度。浏览器将缩小图像(保持长宽比)以适应您指定的大小。您还可以使用这两个规则来指定图像的最小宽度/高度:
min-width
min-height
width
和height
),它应该始终保持纵横比。如果没有,那么在管道的某个地方似乎存在错误。请检查在线演示。如果仍然无法保持纵横比,则应向您正在使用的浏览器的浏览器供应商报告错误。 - starbeamrainbowlabs