gpt4 book ai didi

PHP 图像调整到最小宽度/高度

转载 作者:行者123 更新时间:2023-12-03 23:01:45 25 4
gpt4 key购买 nike

我一直在尝试找出如何在 PHP 中调整上传图像的大小,使其不小于给定大小 (650x650)。但是,如果用户上传的图片已经小于我的任一边缘的最小值 650,则不会采取任何措施。

场景 1 - 上传 2000 像素宽 x 371 像素的图像 - 这不会调整大小,因为 371 像素已经小于我的最小值。

场景 2 - 上传 2000 像素 x 1823 像素的图片 - 在这里我应该将图片的大小调整到尽可能接近最小值,但不允许宽度或高度低于 650 像素。

到目前为止,这是我一直在思考的思路(我正在使用出色的 simpleImage 脚本来帮助调整大小和获取尺寸):

$curWidth = $image->getWidth();
$curHeight = $image->getHeight();
$ratio = $curWidth/$curHeight;

if ($curWidth>$minImageWidth && $curHeight>$minImageHeight)
{
//both dimensions are above the minimum, so we can try scaling
if ($curWidth==$curHeight)
{
//perfect square :D just resize to what we want
$image->resize($minImageWidth,$minImageHeight);
}
else if ($curWidth>$curHeight)
{
//height is shortest, scale that.
//work out what height to scale to that will allow
//width to be at least minImageWidth i.e 650.
if ($ratio < 1)
{
$image->resizeToHeight($minImageWidth*$ratio);
}
else
{
$image->resizeToHeight($minImageWidth/$ratio);
}
}
else
{
//width is shortest, so find minimum we can scale to while keeping
//the height above or equal to the minimum height.
if ($ratio < 1)
{
$image->resizeToWidth($minImageHeight*$ratio);
}
else
{
$image->resizeToWidth($minImageHeight/$ratio);
}
}

然而,这给了我一些奇怪的结果,有时它仍然会低于最小值。它唯一按预期工作的部分是测试尺寸是否超过最小值 - 它不会缩放任何太小的东西。

我认为我最大的问题是我没有完全理解图像纵横比和尺寸之间的关系,以及如何计算出我能够缩放到超出我的最小值的尺寸。有什么建议吗?

最佳答案

试试这个:

$curWidth = $image->getWidth();
$curHeight = $image->getHeight();
$ratio = min($minImageWidth/$curWidth,$minImageHeight/$curHeight);
if ($ratio < 1) {
$image->resize(floor($ratio*$curWidth),floor($ratio*$curHeight));
}

或者这个:

$image->maxarea($minImageWidth, $minImageHeight);

关于PHP 图像调整到最小宽度/高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9467001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com