在PHP中以固定的长宽比打印图像

在显示用户添加的图像时,经常需要调整它们的大小以使其适合页面的特定区域。不这样做可能会导致图像破坏页面布局。问题在于,如果您绝对调整图像的大小,则会倾向于挤压图像并使图像变形。

以下功能可用于将图像的宽度和高度计算为正确的宽高比,当打印输出时将保留内容。该函数利用了该getimagesize()函数,该函数作为PHP的GD库的一部分提供。

/**
 * Calculates the aspect ratio of an image returns a formatted string
 * containing the width and height of the image to a fixed width.
 *
 * @param string  The name of the file
 * @param integer The width of the image (optional)
 *
 * @return string The image dimentions.
 */
function img_aspect_ratio($file, $width = 200){
    if (!file_exists($file)){
        // 文件不存在,返回false。
        return '';
    }
 
    // 获取图像尺寸
    $image_size = getimagesize($file);
 
    if ($image_size === false) {
        // 无法获取图像尺寸,返回宽度
        return ' width="' . $width . '"';
    }
 
    // 将高度除以宽度以获得长宽比。
    $aspect_ratio = $image_size[1] / $image_size[0];
 
    // 根据宽高比更改高度
    $height = (int)($aspect_ratio * $width) . "px";
 
    // 返回格式化的宽度和高度的字符串
    return ' height="' . $height . '" width="' . $width . '"';    
}

您可以使用如下功能:

$image_file = 'example_image.png';
 
echo '<img' . img_aspect_ratio($image_file, 150) . ' xx_src="' . $image_file . '" />';

我应该指出,这种解决方案远非完美,因此不应在所有情况下都使用。最适合调整图像而仅需稍作调整。例如,在画廊中调整缩略图的大小而不必再次重新生成所有缩略图。

不应使用此功能将大图像缩小为小尺寸,因为您的用户在浏览器中调整大小之前仍然需要下载完整大小的图像。在这种情况下,您应该重新生成图像的较小版本,然后将其用作浏览器中图像的源。