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

时间:2012-06-18 19:24:29

标签: php html dynamic scale aspect-ratio

因此经过大量的研究和大量的jQuery和Javascript解决方案,我根本无法找到一种方法来动态地将图像水平和垂直地缩放到指定的大小,我发现大量有关缩放的信息以适应宽度并保持纵横比,或缩放以适应高度并保持纵横比,但无法确定图像是太高还是太短并相应调整。

所以在我的例子中,我有一个<div>,其设置宽度为460px,设置高度为280px,我需要将图像适合,无需拉伸(保持其宽高比) )

2 个答案:

答案 0 :(得分:27)

现在,在摆弄了一些宽度示例之后,我的经典代数技巧开始了。

如果我取宽度并将其除以高度,那么在这种情况下,460/280你得到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 :(得分:2)

如果我理解你的问题,我更简单的缩放图像的方法是使用以下CSS样式规则:

max-width
max-height

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

min-width
min-height
相关问题