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


Dynamically scale images to fit a specified size width and height

因此,经过广泛的研究和大量的jQuery和Javascript解决方案,我根本找不到一种将图像动态缩放到水平和垂直指定大小的方法,我找到了大量关于缩放以适应宽度并保持纵横比的信息,或者缩放以适应高度并保持纵横比, 但无法弄清楚图像是太高还是太矮并相应地进行调整。

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

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

如果我取宽度并将其除以高度,那么在这种情况下,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.'">';

它工作得很好,所以我想我会分享,希望这对一些人有所帮助

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

max-width
max-height

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

min-width
min-height