1

我只是想知道是否有可能获得不同的图像尺寸,并为这些图片创建固定的缩略图尺寸测量,而不会丢失其准确的纵横比。

到目前为止,我已经做了这些:

  • 调整不同图像的大小
  • 保持它们的纵横比
  • 提供相同的尺寸(例如:100px- 高度和 100px- 宽度)

这是我正在使用的代码:

<?php
require("dbinfo.php");

$allPhotosQuery = mysql_query (" SELECT * FROM `placesImages` ");

while ($allPhotosArray = mysql_fetch_assoc ($allPhotosQuery))
{
    $filename= $allPhotosArray['fileName'];
    $placeId = $allPhotosArray['placeId'];

    $imagePath = "placesImages/" . $placeId . "/" . $filename;
    $imageSize = getimagesize($imagePath);

    $imageWidth = $imageSize[0];
    $imageHeight = $imageSize[1];

    $newSize = ($imageWidth + $imageHeight)/($imageWidth*($imageHeight/45));
    $newHeight = $imageHeight * $newSize;
    $newWidth = $imageWidth * $newSize;

    echo "<img src='".$imagePath."' width='".$newWidth."' height='".$newHeight."' />";
}
?>
4

3 回答 3

0

将此函数输入您的原始图像宽度和高度,然后是缩略图限制的最大约束,它将吐出一个数组,其中包含您应该设置缩略图以保持纵横比的 x/y 数组。(任何小于缩略图的都会被放大)

function imageResizeDimensions($source_width,$source_height,$thumb_width,$thumb_height)
{
  $source_ratio = $source_width / $source_height;
  $thumb_ratio = $thumb_width / $thumb_height;
  if($thumb_ratio > $source_ratio)
  {
    return array('x'=>$thumb_height * $source_ratio,'y'=>$thumb_height);
  }
  elseif($thumb_ratio < $source_ratio)
  {
    return array('x'=>$thumb_width,'y'=>$thumb_width/$source_ratio);
  }
  else
  {
    return array('x'=>$thumb_width,'y'=>$thumb_width);
  }
}
于 2012-09-10T23:33:04.863 回答
0

让我们从两个常量thumb_width和开始thumb_height,它们是缩略图所需的宽度和高度。它们可以相等,但不必相等。

如果您的图像宽于高(横向),我们可以将宽度设置为所需的缩略图宽度thumb_width,然后调整高度以保持纵横比。

new_width = thumb_width
new_height = thumb_height * old_height / old_width

请参阅imagecreatetruecolor

然后,您可以移动图像以使其在缩略图范围内垂直居中,从而产生信箱效果。请参阅imagecopyresampled

new_y = (thumb_height - new_height) / 2

对于比它们宽(纵向)高的图像,过程是相同的,但数学有点不同。

new_height = thumb_height
new_width = thumb_width * old_width / old_height

然后您可以在缩略图的范围内将其水平居中。

new_x = (thumb_width - new_width) / 2

有关创建缩略图的基础知识的更多信息,请参阅Resizing images in PHP with GD and Imagick

于 2012-09-11T00:46:15.767 回答
0

除了裁剪之外,在制作缩略图时保持纵横比的最简单方法是执行与您所拥有的类似的操作,但将其设置为固定:

例如,如果你希望所有的 tumbs 都是 100px 宽:

$imageWidth = $imageSize[0];
$imageHeight = $imageSize[1];
$ratio=ImageWidth/$imageHeight;
$newHeight=(int)$ratio*100;
$newWidth=100;

需要注意的是,如果图像有一个有趣的比例,你最终可能会得到一些有趣的尺寸——因为它会很高兴地继续做下去。对代码中的比率进行某种检查可能是个好主意 - 如果它太低或太高,请执行其他操作,否则使用此标准过程。

于 2012-09-10T23:10:18.127 回答