PHP -从图片创建缩略图并保持比例

  • 本文关键字:略图 创建 PHP php image gd
  • 更新时间 :
  • 英文 :


我想创建一个没有黑白条的缩略图,并让它保持长宽比

缩略图的大小应为320x200 (px)。

我实际上写了一个函数来创建给定分辨率的缩略图,但我不知道如何保持图像的长宽比

function imageResize($imageResourceId, $width, $height)
{
$targetWidth = 320;
$targetHeight = 200;
$targetLayer = imagecreatetruecolor($targetWidth, $targetHeight);
imagecopyresampled($targetLayer, $imageResourceId, 0, 0, 0, 0, $targetWidth, $targetHeight, $width, $height);
return $targetLayer;
}

但是我无法找到一种方法来裁剪它们并使它们按照我想要的方式进行调整。提前感谢!

可以使用imagecopyresampled函数,如下所示:

function imageResize($imageResourceId, $width, $height)
{
$targetWidth = 320;
$targetHeight = 200;
$aspectRatio = $width / $height;
$targetRatio = $targetWidth / $targetHeight;
if ($aspectRatio > $targetRatio) {
$newHeight = $targetHeight;
$newWidth = $targetHeight * $aspectRatio;
} else {
$newWidth = $targetWidth;
$newHeight = $targetWidth / $aspectRatio;
}
$targetLayer = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($targetLayer, $imageResourceId, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
return $targetLayer;
}

使用这个,新的宽度和高度是根据原始图像的长宽比计算的。

更多示例:https://www.php.net/manual/en/function.imagecopyresampled.php

最新更新