[英]PHP - Create thumbnail from picture and keeping proportion
I want to create a thumbnail image without black/white bars and have it keep aspect ratio我想创建一个没有黑/白条的缩略图并让它保持纵横比
The thumbnail size should be 320x200 (px).缩略图大小应为 320x200 (px)。
I actually wrote a function to create a thumbnail for a given resolution but I don't know how to keep the aspect ratio of the image我实际上写了一个 function 来为给定的分辨率创建缩略图,但我不知道如何保持图像的纵横比
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;
}
But I can't figure out a way to crop them and have them accommodated as I want.但是我想不出一种方法来裁剪它们并根据需要容纳它们。 Thanks in advance!
提前致谢!
To do this you can use imagecopyresampled function like this:为此,您可以像这样使用 imagecopyresampled function:
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;
}
Using this, the new Width and Height are calculated based on the aspect ratio of the original image.使用这个,新的宽度和高度是根据原始图像的纵横比计算的。
More samples on: https://www.php.net/manual/en/function.imagecopyresampled.php更多示例: https://www.php.net/manual/en/function.imagecopyresampled.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.